Kotlin 类型不匹配:必需 Array<Int?>? 但发现 Array<Int>

Hey*_*ere 2 nullable kotlin kotlin-null-safety

这是我的Foo数据类定义

data class Foo(
    var fooArg: Array<Int?>? = null, 
)
Run Code Online (Sandbox Code Playgroud)

这是对它的调用:

val bar: Array<Int> = arrayOf(1,2,3)
val foo = Foo(fooArg = bar)
Run Code Online (Sandbox Code Playgroud)

但这给出了一个错误type mismatch: required Array<Int?>? but found Array<Int>

我很困惑,它需要一个可为空的类型,而我为它提供了一个非空值,该类型如何不匹配?

Ada*_*hip 6

您声明barArray<Int>. 非空类型与可为空类型*不兼容。将其更改为Array<Int?>,它将起作用:

val bar: Array<Int?> = arrayOf(1,2,3)
val foo = Foo(fooArg = bar)
Run Code Online (Sandbox Code Playgroud)

或者:

val bar = arrayOf<Int?>(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

*我认为正确的说法是数组在类型参数上是不变的。但每次我试图正确理解它时,我都会迷失方向。