在Java中,我可以编写如下代码:
void cast(A a) {
if(a instanceof Person) {
Person p = (Person) a;
}
}
Run Code Online (Sandbox Code Playgroud)
在Kotlin,我该怎么办?使用as运营商或is运营商?
Grz*_*rek 19
is X 相当于 instanceof X
foo as X 相当于 ((X) foo)
此外,Kotlin尽可能执行智能投射,因此在您使用is以下方法检查类型后无需额外投射:
open class Person : A() {
val foo: Int = 42
}
open class A
Run Code Online (Sandbox Code Playgroud)
然后:
if (p is Person) {
println(p.foo) // look, no cast needed to access `foo`
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*hua 12
is是类型检查.但Kotlin有聪明的演员,这意味着你可以使用a类似的Person后检查.
if(a is Person) {
// a is now treated as Person
}
Run Code Online (Sandbox Code Playgroud)
as是类型铸造.但是,as不建议这样做,因为它不保证运行时的安全性.(您可以传递在编译时无法检测到的错误对象.)
科特林有一个安全的演员as?.如果它不能被转换,它将返回null.
val p = a as? Person
p?.foo()
Run Code Online (Sandbox Code Playgroud)