How to cast Any to a List in Kotlin?

Viewed 13985

When I try to cast Any to a List like in the example below I get 'Unchecked cast: Any! to List' warning. Are there any workarounds to this kind of problem?

val x: List<Apples> = objectOfTypeAny as List<Apples>
4 Answers

Solution case for android Serializable to ArrayList:

ModJsonAndDb - your class

private fun serializableToArrayList(obj: Serializable?): ArrayList<ModJsonAndDb>? {
    return if (obj is ArrayList<*>) {
        ArrayList(obj.filterIsInstance<ModJsonAndDb>())
    } else {
        null
    }
}
1. Add:

    inline fun <reified T> List<*>.asListOfType(): List<T>? =
        if (all { it is T })
            @Suppress("UNCHECKED_CAST")
            this as List<T> else
            null

2. Use:

    val list: List<YouType> = someAnyList?.asListOfType<YouType>() 
Related