Search code examples
kotlinkotlin-null-safety

Compact null and emptyness check in Kotlin?


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

Solution

  • 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