【问题标题】:Kotlin compiler error: Type mismatch. Required: CapturedType(out A) Found: AKotlin 编译器错误:类型不匹配。必需:CapturedType(out A) 找到:A
【发布时间】:2020-06-11 07:06:18
【问题描述】:

你能解释一下为什么我会收到这个错误吗?

interface A

open class B<T>

class Foo: A

class Item<T : A>(
    val clazz: Class<out A>,
    val b: B<out A>
)

val items = mutableListOf<Item<out A>>(
    Item(
        Foo::class.java,
        B<Foo>()
    )
)

fun <T : Any?> doSomething(
    type: Class<T>?,
    param: B<T>
) {
    // Nothing
}

fun main() {
    doSomething(items[0].clazz, items[0].b) // compiler error on 2nd argument
    // Type mismatch.
    // Required: CapturedType(out A)
    // Found: A
}

doSomethingB&lt;T&gt; 类型的第二个参数,所以我不明白为什么我无法传递 B&lt;T&gt; 类型的对象?

【问题讨论】:

    标签: kotlin generics compiler-errors


    【解决方案1】:

    doSomethingB&lt;T&gt; 类型的第二个参数,所以我不明白为什么我无法传递 B&lt;T&gt; 类型的对象?

    但是items[0].b 不是B&lt;T&gt; 类型,而是B&lt;out T&gt; 类型。

    如果您将doSomething 的第二个参数转换为B&lt;out T&gt;,它将编译

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多