Careeroza
Safe and Unsafe Casts
as and as?
as casts explicitly and throws ClassCastException if the type is wrong. as? is the safe cast: it returns null instead of throwing.
Example
fun main() {
val values: List<Any> = listOf("42", 7, 3.5)
for (v in values) {
val s: String? = v as? String
println("$v -> ${s ?: "not a String"}")
}
val n = (values[1] as? Int)?.plus(1) ?: 0
println(n)
}Output
42 -> 42 7 -> not a String 3.5 -> not a String 8
Unsafe Cast Failure
Example
fun main() {
val data: Any = 123
val text = data as String
println(text)
}Output
Exception: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
Tip: Prefer is checks with smart casts or as?. Use plain as only when a wrong type really is a bug.