Test object member for null before executing IF bl

2019-08-16 14:12发布

问题:

I have the following code:

class Countries {
    var list: MutableList<String>? = null
}

val countries = Countries()

if (countries.list!!.isNotEmpty()) {

}

At runtime this will raise an exception because list is null. I can do this instead:

if ((countries.list != null) && countries.list!!.isNotEmpty()) {

}

If I had a boolean member called areInitialized that was nullable, I could create a infix function like this:

infix fun Any?.ifTrue(block: () -> Unit) {
    if ((this != null) && this == true) block()
}

and then use it like this:

countries.areInitialized ifTrue {

}

But I can't seem to create something similar for a mutable list.

But I hate having to repeat this test for null on an member field in other parts of code. Is there a simpler way in Kotlin to do this?

回答1:

I would try to stick to the standard as often as you can. So in your example I wouldn't have introduced that ifTrue-function, but rather used takeIf or takeUnless in combination with the safe operator ?. instead, e.g.:

countries?.takeIf { it.areInitialized == true }
         ?.also { 
             /* do something with countries */ 
         }

Or if you must return a value, exchange also with let (or see the other scope functions).

The same then also works for the list within countries:

countries?.takeUnless { it.list.isNullOrEmpty() }
         ?.also { 
             /* do something with countries */ 
             it.list!!.forEach(::println)
         }


标签: kotlin