Kotlin Type Checks & Smart Casts

Using this article, You can learn how to check data type of variable or class of a particular instance at runtime. You can also learn an important feature smart casts in Kotlin.

 

Type Check

In Java, instanceof keyword is used to check of data type. In Kotlin, We have is and !is keywords to check data type of variables.
 
In Java,
if (num1 instanceof Int) {
println(“type is Int”) }
 
In Kotlin,
val num1 = 11
if (num1 is Int) {
println(“type is Int”) }
 
val num1 = “abc”
if (num1 !is Int) {
println(“type is not Int”) }
 
 

Smart Casts

In smart casting, Compiler automatically converts the variable to a particular class reference after it is matched with conditional operator. In many cases, we do not need to use explicit casting in kotlin. We can use smart casts instead of explicit casts in this cases.
 
In Java,
Object obj = “Hello”;
if (obj instanceof String) {
String str = (str) obj;
}
else {
println(“type is not string”);
}
 
In Kotlin,
val str = “Hello”
if (str is String) {
println(“type is string”) // No Type Casting is needed in Kotlin
}
else {
println(“type is not string”)
}
 
 

Explicit Casts

 

Unsafe cast operator: as

If the cast is not possible then cast operator throws an exception. We can call it unsafe cast. For unsafe cast kotlin provides as operator.
 
val obj = “Hello”
val str : String = obj as String
println(str)
 
val obj = 123
val str : String = obj as String
// Throws ClassCastException
 
 

Safe cast operator: as?

If you want to avoid an exception while casting then you need to use safe casting. For this kotlin provides safe cast operator as?.
 
val obj = 123
val str : String? = obj as? String
println(str) // No Exception
 
 

Leave a Reply