I have a list like: `val list: List<Any>` ...
# announcements
a
I have a list like:
val list: List<Any>
How to check its type by the condition ?
when(lists){
is List<Cat> -> {
}
is List<Dog> -> {
}
}
}
Is there any way of doing this stuff? Thanks in advance.
j
Generics are implemented via erasure, so the information about the type inside the list is lost at runtime. There is a way around this by using a reified function. So if lists is a parameter to your function and the function is declared reified (and inline) you can do what you want.
However, you won't be able to use Any, you'll have to use a type parameter in the definition of your function.
d
Easier way of doing this would be by wrapping the list in a sealed class.
Copy code
sealed class AnimalList<T>(val list: List<T>) {
    class Dog(list) : AnimalList<Dog>()
... more
}
Then apply when expression to it
👍 1