我有一個空而不是空的支票:
myLocalVariable: String? = null
//..
if (item.data.propertyList !== null && item.data.propertyList!!.isNotEmpty()) {
myLocalVariable = item.data.propertyList!![0]
}
我不喜歡!!-Operators,我敢打賭 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 = ?
}
uj5u.com熱心網友回復:
不需要任何 if-checks 的最簡單和最緊湊的方法就是:
myLocalVariable = item.data.propertyList?.firstOrNull()
如果您想在這種情況下防止覆寫,null可以這樣做:
myLocalVariable = item.data.propertyList?.firstOrNull() ?: myLocalVariable
uj5u.com熱心網友回復:
有內置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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411483.html
標籤:
下一篇:如何在kotlin中添加串列
