JVM does not remember type parameters at runtime (called "type erasure")
So this check is impossible to do
And not sure why the second thing works, but I think it will do funny things if your
list
is smth like
List<OtherClass>
lemme check
Roukanken
04/21/2021, 7:44 AM
yep:
Copy code
data class ClassA(val v: Int)
data class ClassB(val v: String)
val list: List<Any> = listOf(ClassA(1), ClassA(2), ClassA(2))
if (list as? List<ClassB> != null) {
println(list) // [ClassA(v=1), ClassA(v=2), ClassA(v=2)]
println(list[0].v) // throws ClassCastException
}
g
Grigorii Yurkov
04/21/2021, 7:46 AM
I don't ask compiler to check that this is List of MyClass. I want to check that this is List and cast it to List<MyClass>, because in this particular line of code I know, that it can't be list of any other class but MyClass
r
Roukanken
04/21/2021, 7:59 AM
except that
a is B
is made for checking if
a
is of
B
type
and since we consider
List<A>
different type from
List<B>
then
a is List<A>
should not succeed if
a
is of type
List<B>
except that compiler/runtime can't implement this, so it just forbids you from doing these kind of checks