Casts
The casting concept is supported by many programming languages. Basically, casting is a way to convert an object of one particular type into another type. In Java, we need to cast an object explicitly before accessing its member, or cast it and store it in the variable of the casted type. Kotlin simplifies concept of casting and moves it to the next level by introducing smart casts.
In Kotlin, we can perform a few types of cast:
- Cast objects to different types explicitly (safe cast operator)
- Cast objects to different types, or nullable types to non-nullable types, implicitly (smart cast mechanism)
Safe/unsafe cast operator
In strongly typed languages, such as Java or Kotlin, we need to convert values from one type to another explicitly using the cast operator. A typical casting operation is taking an object of one particular type and turning it into another object type that is its supertype (upcasting), subtype (downcasting), or interface. Let's start with a small reminder of casting that...