Kotlin类型推断失败-类型不匹配“找到的数组* ?,必需的数组*?". [英] Kotlin type inference failed - type mismatch "Found Array<*?>, Required Array<*>?"

查看:398
本文介绍了Kotlin类型推断失败-类型不匹配“找到的数组* ?,必需的数组*?".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到Kotlin的字型系统问题.我在类范围内声明了以下变量:

var planets: ArrayList<Planet>? = null

在构造函数中,我尝试初始化数组,但是遇到类型不匹配错误:

planets = arrayListOf(earth, mars, saturn, jupiter, uranus, neptune, pluto)

错误:

Required: ArrayList<Planet>?
Found: ArrayList<Planet?>

为什么会出现此错误以及如何解决?

解决方案

至少有一个行星(earth, mars, saturn, jupiter, uranus, neptune, pluto)具有可为空的类型Planet?,因此推断出的arrayListOf(earth, ...)类型为ArrayList<Planet?>.

由于ArrayList<Planet>与类型Planet不一致,因此不能安全地为其分配值ArrayList<Planet?>.

要解决此问题,您可以:

  • 确保所有行星的类型都不为空Planet
  • 如果上述不可行,请更改

    var planets: ArrayList<Planet>? = null
    

    var planets = arrayListOf<Planet?>()
    

  • 过滤出null个行星,然后将结果集合分配给planets:

    planets = arrayListOf(*arrayListOf(earth, ...).filterNotNull().toTypedArray())
    

让编译器满意的另一种方法是使planets contravariant 像这样:

var planets: ArrayList<in Planet>? = null

PS.使用 kotlin集合类型 List<T>Set<T>和相应的listOfsetOf,而不是Java的对应类型只要有可能.

I am encountering an issue with Kotlin's type system. I declared the variable as below at class scope:

var planets: ArrayList<Planet>? = null

and in the constructor I try to initialize the array but I am encountering a type mismatch error:

planets = arrayListOf(earth, mars, saturn, jupiter, uranus, neptune, pluto)

error:

Required: ArrayList<Planet>?
Found: ArrayList<Planet?>

Why am I getting this error and how do I fix it?

解决方案

At least one of the planets (earth, mars, saturn, jupiter, uranus, neptune, pluto) is of nullable type Planet? hence the inferred type of arrayListOf(earth, ...) is ArrayList<Planet?>.

Since ArrayList<Planet> is not contravariant on type Planet it cannot be safely to assigned with value ArrayList<Planet?>.

To resolve the problem you can:

  • make sure all planets are of not nullable type Planet
  • if the above is not feasible change

    var planets: ArrayList<Planet>? = null
    

    to

    var planets = arrayListOf<Planet?>()
    

  • filter out null planets and then assign the result collections to planets:

    planets = arrayListOf(*arrayListOf(earth, ...).filterNotNull().toTypedArray())
    

Another way to make the compiler happy is to make the planets contravariant like so:

var planets: ArrayList<in Planet>? = null

PS. Use kotlin collection types List<T>, Set<T> and corresponding listOf, setOf instead of Java's counterparts whenever possible.

这篇关于Kotlin类型推断失败-类型不匹配“找到的数组* ?,必需的数组*?".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆