I know that for checking
if(storesList!=null && storesList.isNotEmpty()){
// do this
} else {
//else do this
}
we can write like this,
storesList?.takeIf { it.isNotEmpty() }.apply {//do this
}
How can i add an else condition to this, I'm not taking about takeUnless
In Kotlin way, you can use safe call operator ('?') to do stuffs on nullable objects without crash or even making it inside if (obj!=null)
block.
So, some object like
if (someObj != null )
someObj.someOperation() //just doing some operation
is the same thing by calling like : someObj?.someOperation()
.
So, if you want to check emptiness of list without if-else condition, you can use like below (Which you've already done).
storesList?.takeIf { it.isNotEmpty() }?.apply {
// Provides you list if not empty
}
But what about else condition here?
For that, you can use elvis operator to satisfy condition. What this operator do is if left hand-side of operation is null or doesn't satisfy specific condition then take right hand-side of operand.
So, final code should look like:
storesList?.takeIf { it.isNotEmpty() }?.apply {
// Provides you list if not empty
} ?: run {
// Else condition here
}
Explanation: if storesList
is empty or null it goes to else part (that is after elvis) otherwise goes to apply block.
You can add an Elvis Operator..
storesList?.takeIf { it.isNotEmpty() }?.apply {
//it.isNotEmpty() is true
} ?: //it.isNotEmpty() is false
So if it.isNotEmpty()
is true, takeIf
returns a non-null value and the apply block will be called.
If false, the expression is null and the elvis operator will execute the expression behind it. The elvis operator is a bit like if (expression before == null)
-> execute statement after elvis operator.
For more information, have a look at the docs: https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With