Is there a reason I cannot write `if (list is List...
# announcements
g
Is there a reason I cannot write
if (list is List<MyClass>)
? Compiler forces me to write
if (list is List<*>)
. So I have to write
if (list as? List<MyClass> != null)
to smartcast my list
r
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
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
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
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