如果我创建一个数组,然后填充它,Kotlin 认为数组中可能存在空值,并强制我考虑这一点
val strings = arrayOfNulls<String>(10000)
strings.fill("hello")
val upper = strings.map { it!!.toUpperCase() } // requires it!!
val lower = upper.map { it.toLowerCase() } // doesn't require !!
Run Code Online (Sandbox Code Playgroud)
创建填充数组就不存在这个问题
val strings = Array(10000, {"string"})
val upper = strings.map { it.toUpperCase() } // doesn't require !!
Run Code Online (Sandbox Code Playgroud)
如何告诉编译器结果strings.fill("hello")是一个 NonNull 数组?
经验法则:如果有疑问,请明确指定类型(对此有一个特殊的重构):
val strings1: Array<String?> = arrayOfNulls<String>(10000)
val strings2: Array<String> = Array(10000, {"string"})
Run Code Online (Sandbox Code Playgroud)
所以你会看到strings1包含可空项,而不strings2包含。仅此一点决定了如何使用这些数组:
// You can simply use nullability in you code:
strings2[0] = strings1[0]?.toUpperCase ?: "KOTLIN"
//Or you can ALWAYS cast the type, if you are confident:
val casted = strings1 as Array<String>
//But to be sure I'd transform the items of the array:
val asserted = strings1.map{it!!}
val defaults = strings1.map{it ?: "DEFAULT"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2937 次 |
| 最近记录: |