Kotlin Check And Cast Type (Safe Cast)

May 10, 2018

The best way is to use is, which check to type and perform an auto cast.

if (obj is String) {
    // notice we can access property .length as it auto cast obj to String
    print(obj.length)
}

NOTE: works for when and while as well

The following cast is unsafe

val text: String = obj as String

Safe nullable cast: return null on failure/exception

val text: String? = obj as? String

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.