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:
- Safe cast (
as?) — attempts to cast the object to the desired type and returnsnullif it is not possible. - Regular cast (
as) — casts the object to the type but throws aClassCastExceptionif 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)
}