Mark
03/19/2023, 3:07 AMfun <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)
asdf asdf
03/19/2023, 5:18 AMfooValue
is implicitly marked as a Boolean, as it is the expected return type of the getValue
methodfoo
is not actually a boolean (possibly from an unchecked cast), so it is fine when the variable type is Any
, but not Boolean
Mark
03/19/2023, 8:23 AMAny
(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.String
ended up in a value for what would normally be a Boolean
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
ilya.gorbunov
03/19/2023, 7:59 PM