Sobes.tech
Junior — Middle

Can you explain the principle of type casting mechanism in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the type casting mechanism allows converting objects from one type to another when necessary. There are two main ways:

  1. Safe cast (as?) — attempts to cast the object to the desired type and returns null if it is not possible.
  2. Regular cast (as) — casts the object to the type but throws a ClassCastException if the cast is not possible.

Example:

val obj: Any = "string"

val str1: String? = obj as? String  // safe cast, str1 will be "string"
val str2: String = obj as String    // regular cast

val num: Int? = obj as? Int         // safe cast, num will be null

Kotlin also supports smart casting after a check with is:

if (obj is String) {
    // Inside this block, obj is automatically cast to String
    println(obj.length)
}