Mark Lisoway
Mark Lisoway

Reputation: 629

Unchecked cast of generic class type IDE warning

For simplification, I have these two classes:

abstract class ClassA<T> where T : ClassA<T> {
    fun fooA(): T {
        //Do stuff
        return this as T //<-- Cast warning happens here
    }
}

open class ClassB : ClassA<ClassB>() {
    fun fooB(): ClassB {
        //Do stuff
        return this
    }
}

That line that I have marked in the fooA function gets flagged by IntelliJ with this warning: "Unchecked cast: ClassA<T> to T". Unless I am missing something, the way I have the classes setup should make it impossible for for the return type in function fooA to not be a child of ClassA meaning the cast check would be redundant. Or at least I can't see a way in which fooA could attempt to cast ClassA to something that is not a child of it. Am I missing something, or am I OK to suppress the warning?

Upvotes: 1

Views: 493

Answers (1)

ice1000
ice1000

Reputation: 6569

The warning is correct. Because you may fill the generic parameter with an evil argument like this:

class ClassC : ClassA<ClassB>()

Now you can produce a ClassCastException simply by calling fooA on ClassC:

fun main(args: Array<String>) {
    val fooA = ClassC().fooA()
}

This is why fooA is unsafe.

Such kind of error cannot be detected at compile time, and this is why the warning is there.

Of course, you can manually ensure your code doesn't fill the generic parameter the wrong way and suppress the warning.

Upvotes: 1

Related Questions