https://kotlinlang.org logo
Title
k

K J

12/29/2018, 7:00 AM
Hey there; Just a little question: Why is this an unchecked cast?
val items = mutableListOf<T>()

override fun <U : T> typedItems(): List<U> {
    return items.mapNotNull { it as? U }
}
but this is not?
val oldStuff = mutableListOf<List<*>>()
val newStuff = oldStuff.mapNotNull { it as? ArrayList<*> }
d

Dico

12/29/2018, 8:30 AM
Because of jvm type erasure at runtime, the cast is unchecked, because it cannot check that the type is U So the cast will succeed and might lead to a runtime error elsewhere.
If your function were not virtual, you could use an inline function with a
reified
type parameter.
k

K J

12/30/2018, 12:04 AM
Got it, alright!