How to cast Any to a List in Kotlin?
Except ignoring the warning (or improving the design to avoid the cast), no.
This warning means that the cast can succeed at runtime even though the list is not actually a List<Apples>
, but contains something other than Apples
.
It exists because generics are not reified in Java. Generics work with type erasure. they're a compile-time safety net, not a runtime safety net.
This is "just" a warning saying that it's not 100% safe just to cast. The better option would be:
if (objectOfTypeAny is List<*>) {
val a: List<Apples> = objectOfTypeAny.filterIsInstance<Apples>()
...
}
See https://kotlinlang.org/docs/reference/typecasts.html for details.