Skip to content
thesarfo

Note

Kotlin: Type Checks & Casts

The is/!is operators, smart casts, and the safe (nullable) cast operator in Kotlin.

views 0

is and !is operators

  • is operator checks if an object is an instance of a type.
  • !is operator checks if an object is not an instance of a type.
fun main(){
val name = "John"
if(name is String){
println("$name is a string")
}
if(name !is Int){
println("$name is not an integer")
}
}

Smart casts

In most cases, you don’t need to use explicit casting in Kotlin. The compiler will automatically cast the variable to the correct type if you check the type before using it.

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

”Safe” (nullable) cast operator

To avoid throwing an exception when casting, you can use the as? operator. If the cast is not possible, the result will be null.

fun main(){
val x: String? = "Hello"
val y: String? = null
val z: Int? = x as? Int // z will be null
val w: Int? = y as? Int // w will be null
}