Compact null and emptyness check in Kotlin?

Viewed 53

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 = ?
}
2 Answers

the easiest and most compact way, without the need of any if-checks is to just do:

myLocalVariable = item.data.propertyList?.firstOrNull()

if you want to prevent overwriting in the case of null you could do it like this:

myLocalVariable = item.data.propertyList?.firstOrNull() ?: myLocalVariable 

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)
}
Related