Can anyone explain what I'm doing wrong here? ``` ...
# announcements
j
Can anyone explain what I'm doing wrong here?
Copy code
fun <T> test(list: List<T>) = when (list) {
    is List<String> -> println("Hello World")
    is List<List<Int>> -> println("Deep")
    else -> println("No Clue")
}
d
Generics are erased. At runtime there is only
List
, so this check is not possible.
r
Let's say I compile your code then decompile it, here's what it would look like:
Copy code
fun test(list: List) = when (list) {
    is List -> println("Hello World")
    is List -> println("Deep")
    else -> println("No Clue")
}
s
that should be a compile error, too,
Cannot check for instance of erased type
👍 1
j
alright thanks 🙂
how would you solve something like this?
e
You might want to reify type argument
e
data class ListOfStrings(val list: List<String>)
& etc — use those instead of plain lists & you’ll be able to check their types.
s
reified won’t make the
is List<T>
check valid - you can match against
T::class
, but that would likely fail against the
List<List<Int>>
case
t
It’s a very bad approach but you could cast
list
to
List<Any>
, then check if
list[0] is String/List