Home > Net >  Compact null and emptyness check in Kotlin?
Compact null and emptyness check in Kotlin?

Time:01-14

I have a null and not empty check:

myLocalVariable: String? = null
//..
if (item.data.propertyList !== null && item.data.propertyList!!.isNotEmpty()) {
    myLocalVariable = item.data.propertyList!![0]
}

I don't like the !!-Operators and I bet there is more beautiful and compact Kotlin way?

PROPOSAL1:

item.data.propertyList?.let {
     if (it.isNotEmpty()) myLocalVariable = it[0]
}

Still I have ?.let and another if clause encapsulated.

PROPOSAL2:

fun List<*>?.notNullAndNotEmpty(f: ()-> Unit){
    if (this != null && this.isNotEmpty()){
        f()
    }
}

Here, it is still not compact, but when used several times, might be helpful. Still I dont know how to access the non empty list:

item.data.propertyList.notNullAndNotEmpty() {
    myLocalVariable = ?
}

CodePudding user response:

There is the built in isNullOrEmpty method:

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)
}
  •  Tags:  
  • Related