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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.