kotlingenericsreflection

How to accept any derived class KClass


I have this code

import kotlin.reflect.KClass

fun <T: Any> test(arr: Array<KClass<T>>) {
    print(arr)
}

fun main() {
    test<Number>(arrayOf(Int::class, Short::class))
}

But this will throw

Type mismatch: inferred type is Number but Int was expected
Type mismatch: inferred type is Short but Int was expected
Type mismatch: inferred type is Number but Short was expected
Type mismatch: inferred type is Int but Short was expected
Type mismatch: inferred type is KClass<Short> but KClass<Int> was expected
Type mismatch: inferred type is KClass<Int> but KClass<Short> was expected
Type mismatch: inferred type is KClass<Short> but KClass<Int> was expected

Everytime I run it

Play


Solution

  • You can make use of use-site variance and change the parameter type to Array<KClass<out T>>.

    import kotlin.reflect.KClass
    
    fun <T: Any> test(arr: Array<KClass<out T>>) {
        print(arr)
    }
    
    fun main() {
        test<Number>(arrayOf(Int::class, Short::class))
    }