在Kotlin中,编写泛型非内联函数时,x is T
会因类型擦除而引发编译器错误.
fun <T> example(foo: Any, bar: T) {
if (foo is T) { // compile error
// ...
}
}
然而,x as? T
是完全好的,它似乎(虽然抛出通常的"未经判断的铸造"警告).为什么编译器不能用(x as? T) != null
替换x is T
?这两者之间有什么区别吗?
fun <T> example(foo: Any, bar: T) {
if ((foo as? T) != null) { // no compile error
// ...
}
}