考虑 KClass 的继承层次结构

问题描述 投票:0回答:1

我想将类型(如

KClass
)作为参数传递给函数。但是,特定类型可能是参数的子类型,但编译器始终期望函数签名中指定的特定类型。

interface A
class Implementation1 : A
class Implementation2 : A

fun showType(aType: KClass<A>) {
    println(aType.simpleName)
}

showType(Implementation1::class) // ⚡wrong parameter type 

可执行示例

如果我尝试编译它,我会得到:

Type mismatch: inferred type is KClass<Implementation1> but KClass<A> was expected

因此,虽然 Implements1 实现了预期的接口

A
,但继承似乎被反射忽略了。

有没有办法通过反射接受派生类型?

kotlin inheritance reflection
1个回答
0
投票

正如Jorn所指出的,类型参数

A
需要使用out注释来实现
协变

fun showType(aType: KClass<out A>) { 
  // "out" does the trick  ^^^ 
  println(aType.simpleName)
}

因此

A
的此类子类型被接受为
A

请参阅有关泛型的文档

© www.soinside.com 2019 - 2024. All rights reserved.