benleggiero
03/11/2018, 5:03 PMclass Foo<Bar>(
initial: Bar?
) {
private val internal: Any? = initial
fun baz(): Bar? {
val i = internal
return if (i is Bar) i
else null
}
}
Error: Cannot check for instance of erased type: Bar
diesieben07
03/11/2018, 5:11 PMBar
is not retained at runtime. Foo<Int>
and Foo<String>
are the same class at runtime. So you cannot know what the actual type of Bar
is.benleggiero
03/11/2018, 5:13 PMbenleggiero
03/11/2018, 5:13 PMas!! Bar
and it’s not a Bar
?diesieben07
03/11/2018, 5:15 PMas!!
. And no. It can't. It will create a warning ("Unchecked cast"). What you then have is called heap pollution. You will get the class cast exception at some point down the line when someone actually tries to use the object as it's true type.benleggiero
03/11/2018, 5:20 PMas
, as?
and as!
benleggiero
03/11/2018, 5:20 PMdiesieben07
03/11/2018, 5:21 PMdiesieben07
03/11/2018, 5:22 PMval listOfStrings = mutableListOf<String>("Hello")
doEvilStuff(listOfStrings, 1)
println(listOfStrings[1]) // will crash, Int is not a String
fun <T> doEvilStuff(list: MutableList<T>, number: Int) {
list += number as T // will not crash, because this method does not know what `T` is!
}
benleggiero
03/11/2018, 5:24 PMdiesieben07
03/11/2018, 5:25 PMreified
keyword with inline
function.benleggiero
03/11/2018, 5:25 PMdiesieben07
03/11/2018, 5:25 PMbenleggiero
03/11/2018, 5:26 PMdiesieben07
03/11/2018, 5:26 PMClass<Bar>
or KClass<Bar>
benleggiero
03/11/2018, 5:32 PMhttps://i.imgur.com/8ZiJwla.png▾
diesieben07
03/11/2018, 5:33 PMKClass
of a nullable type.benleggiero
03/11/2018, 5:33 PMdiesieben07
03/11/2018, 5:33 PMValue
have any upper bound?diesieben07
03/11/2018, 5:34 PMAny?
, which is definitely nullable.benleggiero
03/11/2018, 5:35 PMclass Foo<Bar>(
initial: Bar?,
val barClass: KClass<Bar>
) {
private val internal: Any? = initial
fun baz(): Bar? {
val i = internal
return if (i is Bar) i
else null
}
}
Type argument is not within its bounds
Expected: Any
Found: Bar
diesieben07
03/11/2018, 5:35 PMAny?
.diesieben07
03/11/2018, 5:35 PMbenleggiero
03/11/2018, 5:35 PMFoo<Bar>
to Foo<Bar: Any>
diesieben07
03/11/2018, 5:35 PMbenleggiero
03/11/2018, 5:35 PM?
as “wrapped in an `Optional`”benleggiero
03/11/2018, 5:36 PM