...

/

Explicit vs. Smart Casting

Explicit vs. Smart Casting

Learn to handle type conversion challenges and leverage smart-casting features for safer and more efficient coding practices.

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).

Press + to interact
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 ...