我有一个空且非空的检查:
myLocalVariable: String? = null
//..
if (item.data.propertyList !== null && item.data.propertyList!!.isNotEmpty()) {
myLocalVariable = item.data.propertyList!![0]
}
我不喜欢!!
-运算符,我打赌还有更漂亮、更紧凑的Kotlin方式吗?
提议1:
item.data.propertyList?.let {
if (it.isNotEmpty()) myLocalVariable = it[0]
}
我仍然封装了?.let
和另一个if
子句。
建议2:
fun List<*>?.notNullAndNotEmpty(f: ()-> Unit){
if (this != null && this.isNotEmpty()){
f()
}
}
在这里,它仍然不紧凑,但如果多次使用,可能会有所帮助。我仍然不知道如何访问非空列表:
item.data.propertyList.notNullAndNotEmpty() {
myLocalVariable = ?
}
最简单、最紧凑的方法,无需任何if检查,只需执行:
myLocalVariable = item.data.propertyList?.firstOrNull()
如果你想在null
的情况下防止覆盖,你可以这样做:
myLocalVariable = item.data.propertyList?.firstOrNull() ?: myLocalVariable
有内置的isNullOrEmpty
方法:
if (!item.data.propertyList.isNullOrEmpty()) {
// provided that propertyList is a val, you do not need !! here
myLocalVariable = item.data.propertyList[0]
// otherwise, use "?."
// myLocalVariable = item.data.propertyList?.get(0)
}