Type checks and casts
In Kotlin, you can perform type checks to check the type of an object at runtime. Type casts convert objects to a different type.
is and !is operators
is operator or its negated form
!is to perform a runtime check that identifies whether an object conforms to a given type:
In most cases, you don't need to use explicit cast operators in Kotlin because the compiler tracks the
is-checks and explicit casts for immutable values and inserts (safe) casts automatically when necessary:
The compiler is smart enough to know that a cast is safe if a negative check leads to a return:
Or if it is on the right-hand side of
|| and the proper check (regular or negative) is on the left-hand side:
Smart casts can be used in the following conditions:
Always, except local delegated properties.
If the property is
If the variable is not modified between the check and its usage, is not captured in a lambda that modifies it, and is not a local delegated property.
Never, because the variable can be modified at any time by other code.
"Unsafe" cast operator
Usually, the cast operator throws an exception if the cast isn't possible. Thus, it's called unsafe. The unsafe cast in Kotlin is done by the infix operator
null cannot be cast to
String, as this type is not nullable. If
y is null, the code above throws an exception. To make code like this correct for null values, use the nullable type on the right-hand side of the cast:
"Safe" (nullable) cast operator
To avoid exceptions, use the safe cast operator
as?, which returns
null on failure.
Note that despite the fact that the right-hand side of
as? is a non-nullable type
String, the result of the cast is nullable.