kotlin - 类型不匹配:推断类型是 MutableList<TypeA> 但 MutableList<InterfaceType> 是预期的
kotlin - Type mismatch: inferred type is MutableList<TypeA> but MutableList<InterfaceType> was expected
我正在尝试用 kotlin 编写一些代码,但我遇到了一些问题。我怎样才能解决这个问题?我分享了我的代码。请帮助我!
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
interfaceTypeList = typeAList
}
这与 Kotlin 类型有关 variance
。
类型 MutableList<T>
在其类型 T
中是 不变的 因此您不能将 MutableList<InterfaceType>
分配给 MutableList<TypeA>
.
为了能够分配它,因为 InterfaceType
是 TypeA
的超类型,您需要 class 协变 在其类型中(例如 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<InterfaceType>
.
进行未经检查的转换
```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>
}
我正在尝试用 kotlin 编写一些代码,但我遇到了一些问题。我怎样才能解决这个问题?我分享了我的代码。请帮助我!
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
interfaceTypeList = typeAList
}
这与 Kotlin 类型有关 variance
。
类型 MutableList<T>
在其类型 T
中是 不变的 因此您不能将 MutableList<InterfaceType>
分配给 MutableList<TypeA>
.
为了能够分配它,因为 InterfaceType
是 TypeA
的超类型,您需要 class 协变 在其类型中(例如 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<InterfaceType>
.
```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>
}