Kotlin Smart Casts

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.

instanceof Java Example
1
2
3
4
5
6
public class InstanceofExample {	
public static void main(String[] args) {
MyClass obj=new MyClass();
System.out.println(obj instanceof MyClass);//true
}
}

In Kotlin, You can check whether an object is of a certain type at runtime by using the is operator.

is operator Kotlin Example
1
2
3
4
5
6
7
8
9
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

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:

Smart Casts Kotlin Example
1
2
3
4
5
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:

Smart Casts Kotlin Example
1
2
if (x !is String) return
print(x.length) // x is automatically cast to String

Such smart casts work for when-expressions and while-loops as well:

Smart Casts Kotlin Example
1
2
3
4
5
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}

Share Comments