【问题标题】:kotlin - Type mismatch: inferred type is MutableList<TypeA> but MutableList<InterfaceType> was expectedkotlin - 类型不匹配:推断类型是 MutableList<TypeA> 但 MutableList<InterfaceType> 是预期的
【发布时间】:2020-07-23 01:18:52
【问题描述】:

我正在尝试在 kotlin 中编写一些东西,但我遇到了一些问题。我怎样才能解决这个问题?我分享我的代码..请帮助我!

interface InterfaceType {}

open class ConcreteImpl: InterfaceType {}

class TypeA: ConcreteImpl() {}

fun test() {

    var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()

    var typeAList: MutableList<TypeA> = mutableListOf()

    interfaceTypeList = typeAList

}

You can show the code from here.

【问题讨论】:

  • 嗨,我知道你是新来的。如果您认为某个答案解决了问题,请将其标记为已接受。

标签: kotlin inferred-type


【解决方案1】:

这与 Kotlin 类型 variance 有关。

MutableList&lt;T&gt; 类型在其T 类型中不变,因此您不能将MutableList&lt;InterfaceType&gt; 分配给MutableList&lt;TypeA&gt;

为了能够分配它,因为InterfaceTypeTypeA 的超类型,您需要在其类型中改为一个类covariant(例如List)。

interface InterfaceType {}

open class ConcreteImpl: InterfaceType {}

class TypeA: ConcreteImpl() {}

fun test() {
    var interfaceTypeList: List<InterfaceType> = mutableListOf()
    var typeAList: MutableList<TypeA> = mutableListOf()
    interfaceTypeList = typeAList
}

否则,您应该对MutableList&lt;InterfaceType&gt; 进行未经检查的强制转换。

```kotlin
interface InterfaceType {}

open class ConcreteImpl: InterfaceType {}

class TypeA: ConcreteImpl() {}

fun test() {
    var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
    var typeAList: MutableList<TypeA> = mutableListOf()
    // Unchecked cast.
    interfaceTypeList = typeAList as MutableList<InterfaceType>
}

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 2018-04-23
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多