Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add else condition to takeIf in kotlin?

Tags:

android

kotlin

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

like image 937
Manoj Perumarath Avatar asked Jun 25 '19 05:06

Manoj Perumarath


2 Answers

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.

like image 117
Jeel Vankhede Avatar answered Oct 07 '22 01:10

Jeel Vankhede


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

like image 9
the_dani Avatar answered Oct 07 '22 00:10

the_dani