Kotlin Cast Any to List or Map: Unchecked Cast

March 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)

or

val ids = items as? List<*>
for (id in ids) {
    if (id is String) {
        // do something
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.