Hello! Could somebody answer me, why “is T”( T is ...
# kotlin-native
d
Hello! Could somebody answer me, why “is T”( T is type Parameter) don’t work due to type erasure, but “as T” work fine in the same conditions(only case is unchecked)? I thought due to type erasure both of them shouldn’t work, as T type will not be available in runtime( for example in function call) Thanks
l
Checking 'is T' requires the runtime to know the type of T (if I have a List<T>, is T an Int? a double?), but casting is a promise. You're telling the compiler 'I know that list[0] is an Int, and I'm willing to deal with an exception if not'.
I believe you can check 'is T' for an inline function, since it can replace 'T' with the actual type when inlining, but not otherwise.
d
Environment: we don’t use reified parameters/inline. So as I undrstand, all ‘as T’ are substituted by the compiler with ‘as Int’ (if T is Int in the call site), but ‘is T’ couldn’t? What does it mean ‘as T’ - promise?If ‘as T’ will be done the same way in runtime?
thanks for the answer
l
It can only replace the type in inline methods. When you cast to a generic, it's just a promise. You don't have to know what the type is, you're just promising it's the right type. For example:
Copy code
class Holder<T>(value: T) {
    val something: Any = value
    
    fun getValue(): T = something as T
}
Code written on my phone, so could have problems. When you call getValue on a Holder<Int>, the compiler expects the return type to be Int, since at the call site, the type is known. The cast inside of getValue doesn't know it's an Int, so you're just promising the compiler 'whatever type it's returning, I know it matches T'.
d
got you. Thank you for the explanation. I just decompiled to java code, and it’s just cast to Object