Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading