Type Checks and Casts

Type Checks and Casts

is and !is Operators

We can check whether an object conforms to a given type at runtime by using the is operator or its negated form !is:

if (obj is String) {
    print(obj.length)
}

if (obj !is String) { // same as !(obj is String)
    print("Not a String")
}
else {
    print(obj.length)
}

Smart Casts

In many cases, one does not need to use explicit cast operators in Kotlin, because the compiler tracks the is-checks for immutable values and inserts (safe) casts automatically when needed:

fun demo(x: Any) {
    if (x is String) {
        print(x.length) // x is automatically cast to String
    }
}

The compiler is smart enough to know a cast to be safe if a negative check leads to a return:

登录查看完整内容