https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

03/19/2023, 3:07 AM
I kind of understand what is happening here, but how best to explain it?
Copy code
fun <T> Foo<T>.getValue(): T

val foo: Foo<Boolean> = ...
println("no problem: " + foo.getValue())
val fooAnyValue: Any = foo.getValue()
println("also no problem: " + fooAnyValue)
val fooValue = foo.getValue()
println("class cast exception (fooValue is not a Boolean): " + fooValue)
a

asdf asdf

03/19/2023, 5:18 AM
The type of
fooValue
is implicitly marked as a Boolean, as it is the expected return type of the
getValue
method
However it seems like the value of
foo
is not actually a boolean (possibly from an unchecked cast), so it is fine when the variable type is
Any
, but not
Boolean
m

Mark

03/19/2023, 8:23 AM
Yes, it’s interesting that we can get access to such an illegal value by assigning to a property of type
Any
(or by passing it straight into some place that accepts
Any
) and so avoid the
ClassCastException
. However with
val fooValue = foo.getValue()
there is an implicit type
Boolean
of
fooValue
and so the class cast cannot be avoided. A part of me thinks that when getting the value there should be a check/exception regardless.
For context, I’m playing around with Android Jetpack DataStore which stores different types in a big map. So I’m checking what would happen if, say, a random
String
ended up in a value for what would normally be a
Boolean
If I want to add my own check, is there a way (perhaps using an inline function with reified type) to ensure the value is the correct type? Indeed, we can do this:
Copy code
inline fun <reified T> Foo<T>.getValueSafely(): T? = getValue() as? T
Even though the compiler says “No cast needed” it does actually avoid the
ClassCastException
i

ilya.gorbunov

03/19/2023, 7:59 PM
3 Views