Kotlin type inference failed - type mismatch “Found Array<*?>, Required Array<*>?”

前端 未结 2 2167
甜味超标
甜味超标 2021-01-04 21:08

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

var planets: ArrayList? = null
<         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 21:52

    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.

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

    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? = null
      

      to

      var planets = arrayListOf()
      
    • 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? = null
    

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

提交回复
热议问题