Many times while working we need to check if an object is of certain type at runtime.
In java we have instanceof
operator to check whether the object is an instance of the specified type.
1 | public class InstanceofExample { |
In Kotlin, You can check whether an object is of a certain type at runtime by using the is
operator.
1 | if (obj is String) { |
Smart Casts
Kotlin Complier is quite smart and help us to avoid boilerplate code.
In many cases we do not need to use explicit cast operators , because the compiler tracks the is -checks and explicit casts for immutable values and inserts (safe) casts automatically when needed:
1 | fun demo(x: Any) { |
The compiler is smart enough to know a cast to be safe if a negative check leads to a return:
1 | if (x !is String) return |
Such smart casts work for when-expressions and while-loops as well:
1 | when (x) { |