我有这个代码

import kotlin.reflect.KClass

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

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

但这会抛出

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

每次我运行它的时候

Play

推荐答案

您可以使用use-site variance,并将参数类型更改为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))
}

Kotlin相关问答推荐

在Kotlin中可以连接两个范围吗?

在kotlin中使用List(mylist. size){index—TODO()}或Map迭代>

如何确保Kotlin子类已完成初始化?

映射中列表类型的Kotlin可空接收器?

如何访问方法引用的接收者?

我可以更改方法中泛型类的类型参数边界吗?

如何检测一个值是否是Kotlin中的枚举实例?

Kotlin 中命名构造函数的惯用方式

Kotlin 获取继承类的默认 hashCode 实现

用于将 0.5 变为 0 的 round() 函数的模拟

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

返回 kotlin 中的标签和 lambda 表达式

parallelStream()和asSequence().asStream().parallel()之间的区别

无法解决:androidx.lifecycle:lifecycle-viewmodel-ktx:1.1.1

Kotlin的web-framework框架

用mockk验证属性设置程序吗?

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

应用程序在使用 Google Play 服务时遇到问题

旋转 kotlin 数组

有没有办法在Kotlin中设置一个私有常量