Search code examples
javagenericskotlincovariance

Kotlin Generic Reflection Subclass


I have a function that takes a Class<GenericType<Constraint>>. When I pass a subclass of that GenericType<Constraint> the compiler errors with the message: Type Inference Failed. Expected Type Mismatch

However, if I cast the type to it's supertype, it runs fine (with a warning). How to do this without casting?

open class Bag<T>

class IntBag: Bag<Int>()

fun testStuff(type: Class<Bag<Int>>) {
    // Do stuff
}

testStuff(IntBag::class.java) // This won't compile
testStuff(IntBag::class.java as Class<Bag<Int>>) // This compiles with a warning, but runs fine

Solution

  • You'll have to use out variance: fun testStuff(type: Class<out Bag<Int>>)

    https://kotlinlang.org/docs/reference/generics.html