Kotlin smartcast check is failing despite type information being available at runtime

35 views Asked by At

Essentially what I'm trying to do is smartcast an object at runtime if the variable has been set to an object of the specified type. However, the object itself is a generic type. The is type check is returning false at runtime, yet the type information is available at runtime, as evidenced by printing the class name.

So my code looks something like this:

val desiredObject = genericTypeWrapper.genericType

println("desiredObject is of type: {}", desiredObject::class.simpleName)

if (desiredObject is MyType) {
    println("desiredObject is MyType")
    // Do something with desiredObject
}

It'll compile, and the first print statement above would show: desiredObject is of type: MyType, but the if condition returns false every time.


Since desiredObject is a generics type, I tried an inline function with reified type, something like this:

inline fun <reified T> getMyType(genericTypeWrapper: GenericTypeWrapper): T? {
    val desiredObject = genericTypeWrapper.genericType

    println("desiredObject is of type: {}", desiredObject::class.simpleName)

    if (desiredObject is T) {
        return desiredObject
    }
    
    return null
}

I then call it like so:

desiredObject = getMyType<MyType>(genericTypeWrapper)

Assuming correct input to desiredObject (verified manually), the if condition should return true and execute code inside the block. However, this also fails like the previous example, where the print statement would read desiredObject is of type: MyType, but the is check is returning false.


Similar code works in Java, using instanceOf. I suspect that the issue comes down to type erasure, hence the above attempt. Any ideas what I'm doing wrong and/or any suggestions to get around this? I'd like to avoid an explicit as? cast, because the object itself is rather large, and is causing significant performance issues.

0

There are 0 answers