Kotlin Cast Any to List or Map: Unchecked Cast

Mar 31, 2019

When casting Any? to List<String>, there is a warning of Unchecked Cast: Any? to List<String>.

// items is Any?val ids = items as List<String>

If you trust the source to contain the appropriate type, you use

@Suppress("UNCHECKED_CAST")val ids = items as? List<String>

For UNCHECKED_CAST in object constructor or function parameters.

@Suppress("UNCHECKED_CAST")val item = Quote(    mainTags = mainTags as? List<String>    )

If you don't trust the source and want to do runtime checking and verification

val ids = items as? List<*>if (ids != null) {    for (id in ids.filterIsInstance<String>()) {        // do something    }}

NOTE: filterIsInstance only return elements which match the type (and remove those who doesn't)


val ids = items as? List<*>for (id in ids) {    if (id is String) {        // do something    }}

❤️ 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.