Kotlin 泛型类型不匹配

Kotlin Generics Type Mismatch

    fun <R, F : Function<R>?, K : KFunction<R>?> Array<F>.reflect(): Array<K> = this.map<F, K> { it?.reflect<R>() }.toTypedArray()

map 的 lambda 中的编译时错误

Type mismatch: inferred type is KFunction<R>? but K was expected

The source of confusion on my part is that why KFunction<R>? is not K if K is defined to be any subtype of KFunction<R>?

正如你所说 KKFunction<R> 的子类型,但 Function<R>.reflect() 不是 return K,它 return 是 KFunction<R>,其中需要 K 类型的值。考虑这个例子:

class A : KFunction<String> {
    // ...implements all methods of KFunction<String>
}

arrayOf({ "foo" }).reflect<String, () -> String, A>()
  • RString
  • FFunction<String>
  • KA,一个扩展 KFunction<String>
  • 的 class

现在为了满足函数,it?.reflect<R>() 部分应该 return 类型 A 的值,但它 return 是 KFunction<String>

也许您为想要实现的目标声明了太多类型参数?这个功能怎么样:

fun <R> Array<out Function<R>?>.reflect(): Array<KFunction<R>?> =
        this.map { it?.reflect<R>() }.toTypedArray()

如有任何问题,请发表评论。