Explicit vs. Smart Casting
Learn to handle type conversion challenges and leverage smart-casting features for safer and more efficient coding practices.
We'll cover the following...
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).
fun main() {val i: Int = 123val l: Long = 123Lval d: Double = 3.14var number: Number = i // up-casting from Int to Numberprintln("Value of number after up-casting from Int: $number")number = l // up-casting from Long to Numberprintln("Value of number after up-casting from Long: $number")number = d // up-casting from Double to Numberprintln("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 ...