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