``` class CliOption2<T>(additionalPropert...
# getting-started
s
Copy code
class CliOption2<T>(additionalProperties: MutableMap<String, Any>) {
        val value by lazy {
            val t = additionalProperties[cliOption.opt]!! as? T
            t ?: throw NotImplementedError("cli option could not be casted")
            t
} how can i fix the cast warning here? I thought me throwing something if it fails would work. Why is it still considered unsafe and how can i fix this?
e
generic types are erased at runtime, so
as? T
doesn't actually know what
T
is and always succeeds even if it's not correct
r
In general, types are effectively replaced by their upper bound at runtime, so
T
in your case is effectively
Any?
, and since everything is indeed
Any?
, it's always true.
s
ah, that's a good expalanation
so there's no way around this except to add a suppress warning?
i thought kotlin had fixes for type erasure, but it looks like those only really apply for Array types
r
Kotlin has
reified generics
, but that only applies to functions that are inlined at compile time, and thus the generic doesn't exist at runtime.
s
i was thinking about reified
r
As far as a way around it, there are potential options if you rework your types to include more information, but that's only if you have that information available somehow.
e
Array is magical on JVM in general, for historical reasons - T[] is a unique type for every (erased) type T, including other array types. but that was in Java before generics, and when they added generics they didn't change any bytecode semantics, so that magic doesn't apply to anything other than arrays
if you passed a
val kclass: KClass<T>
then you could use that to check
isInstance
. (you'd still have an unsafe check but at least you'd have a justifiable reason to suppress)
1
s
ah that is a good point, Arrays are unique in jvm
e
only inline functions can be reified, not classes or constructors, so given this code structure, you don't have many other options
s
well in that case, i could just change the prop to be an inline function right?
e
not sure what you mean
s
the
val value by lazy
could be changed to a inline getValue() {}
with a reified <T> i guess. right?
e
the type would be determined by the callsite
if that makes sense for you, then sure
s
gotcha