首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >kotlin -类型错配:推断类型为MutableList<TypeA>,但MutableList<InterfaceType>是预期的

kotlin -类型错配:推断类型为MutableList<TypeA>,但MutableList<InterfaceType>是预期的
EN

Stack Overflow用户
提问于 2020-04-10 09:51:11
回答 1查看 1.9K关注 0票数 0

我试着用kotlin编码一些东西,但我有一些问题。我怎样才能解决这个问题?我分享我的密码..。请帮帮我!

代码语言:javascript
复制
interface InterfaceType {}

open class ConcreteImpl: InterfaceType {}

class TypeA: ConcreteImpl() {}

fun test() {

    var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()

    var typeAList: MutableList<TypeA> = mutableListOf()

    interfaceTypeList = typeAList

}

你可以在这里展示代码。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-10 10:09:52

这与Kotlin类型variance有关。

类型MutableList<T>在其类型T中是不变,因此不能将MutableList<InterfaceType>分配给MutableList<TypeA>

为了能够分配它,因为InterfaceTypeTypeA的超级类型,您需要一个类型为的协变类(例如List)。

代码语言:javascript
复制
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>进行未经检查的强制转换。

代码语言:javascript
复制
```kotlin

接口InterfaceType {}

打开类ConcreteImpl: InterfaceType {}

类TypeA: ConcreteImpl() {}

有趣的测试(){

代码语言:javascript
复制
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
代码语言:javascript
复制
var typeAList: MutableList<TypeA> = mutableListOf()
代码语言:javascript
复制
// Unchecked cast.
代码语言:javascript
复制
interfaceTypeList = typeAList as MutableList<InterfaceType>

}

代码语言:javascript
复制
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61137789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档