Grigorii Yurkov
04/21/2021, 7:38 AMif (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 listRoukanken
04/21/2021, 7:40 AMlist
is smth like List<OtherClass>
lemme checkRoukanken
04/21/2021, 7:44 AMdata 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
}
Grigorii Yurkov
04/21/2021, 7:46 AMRoukanken
04/21/2021, 7:59 AMa 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