Kotlin类型推断失败 - 类型不匹配"Found Array <*?>,Required Array <*>?"

Sim*_*bes 8 kotlin

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

var planets: ArrayList<Planet>? = null
Run Code Online (Sandbox Code Playgroud)

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

planets = arrayListOf(earth, mars, saturn, jupiter, uranus, neptune, pluto)
Run Code Online (Sandbox Code Playgroud)

错误:

Required: ArrayList<Planet>?
Found: ArrayList<Planet?>
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误,如何解决?

mie*_*sol 8

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

由于ArrayList<Planet>不是类型的逆变,Planet因此不能安全地赋值ArrayList<Planet?>.

要解决此问题,您可以:

使编译器满意的另一种方法是使planets 逆变器如下:

var planets: ArrayList<in Planet>? = null
Run Code Online (Sandbox Code Playgroud)

PS.使用科特林集合类型 List<T>,Set<T>以及相应的listOf,setOf而不是Java的同行只要有可能.