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>
我很困惑,它需要一个可为空的类型,而我为它提供了一个非空值,该类型如何不匹配?
您声明bar为Array<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)
*我认为正确的说法是数组在类型参数上是不变的。但每次我试图正确理解它时,我都会迷失方向。
| 归档时间: |
|
| 查看次数: |
2691 次 |
| 最近记录: |