Search⌘ K
AI Features

Explicit vs. Smart Casting

Explore how Kotlin manages type casting, including explicit casting with the as operator and the safer smart-casting feature. Understand when and how to use these techniques to avoid runtime errors and write reliable Kotlin code.

Explicit casting

We can always use a value whose type is Int as a Number because every Int is a Number. This process is known as up-casting because we change the value type from lower (more specific) to higher (less specific).

Kotlin 1.5
fun main() {
val i: Int = 123
val l: Long = 123L
val d: Double = 3.14
var number: Number = i // up-casting from Int to Number
println("Value of number after up-casting from Int: $number")
number = l // up-casting from Long to Number
println("Value of number after up-casting from Long: $number")
number = d // up-casting from Double to Number
println("Value of number after up-casting from Double: $number")
}

We can implicitly cast from a lower type to a higher one, but not the other way around. Every Int is a Number, but not every Number is an Int because there are more subtypes of Number, including Double or Long. This is why we cannot use Number where Int is expected. However, sometimes we have a situation where we are certain that a value is of a specified type, even though its supertype is used. Explicitly changing from a higher type to a lower type is called down-casting ...