有一个数组:我在下面的代码中notes: Array<KeyValueNote>?
使用了 Kotlin 。1.0.5-2
我想
if (notes != null) {
for (note in notes) {
// Put the note to the payload Json object only if the note is non-null.
payloadJson.put(note.key, note.value)
}
}
但是有几个变种
// Alternative 1.
notes?.let {
it.takeWhile { it != null /** Inspection will note The condition 'it != null' is always true' in here**/ }.forEach { payloadJson.put(it.key, it.value) }
}
// Alternative 2.
notes?.takeWhile { it != null /** Inspection will note The condition 'it != null' is always true' in here**/ }?.forEach { payloadJson.put(it.key, it.value) }
// Alternative 3.
notes?.filterNotNull()?.forEach { payloadJson.put(it.key, it.value) }
我的问题
- 可以看到备
The condition 'it != null' is always true
选项1&2中有检查说明,检查是否正确?因为我想确保只有非空项目notes
可以放入payloadJson
. - 在备选方案 3 中,您可以看到有一个 Safe Call in
filterNotNull()?.
,这里是否?
需要 ?,因为我查看了源代码,结果filterNotNull()
不能为空,但是当我在其中删除?
时,编译失败。