1

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?

Mark Lisoway
  • 619
  • 1
  • 6
  • 20
  • Good question. This shows the weakness of Java's (as well as Kotlin's) type system. `typeclass` resolves this. – ice1000 Apr 30 '18 at 04:06

1 Answers1

1

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.

ice1000
  • 6,406
  • 4
  • 39
  • 85
  • Ah, I see the issue now. You can't do type checking generics though (not that it would help this issue). Is manually making sure I don't make those generic type erros a reasonable path to take? Or do you know if there is a known solution to get around this problem? – Mark Lisoway Apr 30 '18 at 04:42
  • This shows the weakness of Java's (as well as Kotlin's) type system. `typeclass` (a language feature, Haskell/Scala have this) resolves this. Take a look at [my old question](https://stackoverflow.com/q/47861636/7083401) which is looking for the similar stuff. – ice1000 Apr 30 '18 at 04:44