How to add else condition to takeIf in kotlin?

Use Elvis Operator

eg.) a ?: b // here ifais not null value =a else value=b

in your case -

storesList?.takeIf { it.isNotEmpty() }?.apply {
    //it.isNotEmpty() is true
} ?: run{} //`else condition goes here`

for more check here - https://en.wikipedia.org/wiki/Elvis_operator


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


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.

Tags:

Android

Kotlin