我试着用kotlin编码一些东西,但我有一些问题。我怎样才能解决这个问题?我分享我的密码..。请帮帮我!
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
interfaceTypeList = typeAList
}发布于 2020-04-10 10:09:52
这与Kotlin类型variance有关。
类型MutableList<T>在其类型T中是不变,因此不能将MutableList<InterfaceType>分配给MutableList<TypeA>。
为了能够分配它,因为InterfaceType是TypeA的超级类型,您需要一个类型为的协变类(例如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接口InterfaceType {}
打开类ConcreteImpl: InterfaceType {}
类TypeA: ConcreteImpl() {}
有趣的测试(){
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()var typeAList: MutableList<TypeA> = mutableListOf()// Unchecked cast.interfaceTypeList = typeAList as MutableList<InterfaceType>}
https://stackoverflow.com/questions/61137789
复制相似问题