‘takeIf’ and ‘takeUnless’ : Kotlin


Ever thought of chaining an if condition?
What if we can chain the if condition also and moves or executes the next code in the chain only if the condition is true?

Kotlin has something very interesting to achieve the same.
We can use takeIf and takeUnless to achieve the same. As clear from the name itself, takeIf will proceed in the chain only if the condition inside is true whereas takeUnless is the counter of takeIf and will proceed only if the provided condition is false.
    </br>
    </br>
    <mark>takeIf</mark> is a filtering function for a single object whereas <mark>takeUnless</mark> is a counter of <mark>takeIf</mark>.
    </br>
    </br>
    Let’s take an example to understand the same.
  
fun getLatency():Int {
return (0..30).random()
}

val networkLatency = getLatency()
println(networkLatency)
if (networkLatency < 20){
// join the game
println("can join the game with latency $networkLatency")
}
In the above example, we need to check the latency of the network and join the game only it is less than 20. Now to achieve the same we need to put an if condition, the reason I need to introduce a new variable networkLatency is because I need to pass it to the inner function also.
Now to achieve the same within single chaining, I can use takeIf.
  
getLatency()?.takeIf{ it < 20}
?.let{
println("can join the game with latency $it")
}
Please note that both takeIf and takeUnless returns null if the condition is not satisfied, so to chain it further we need to use the safe call or null check.

Let's take an example of takeUnless.
  
getLatency()?.takeUnless{ it < 20}
?.let{
println("warning : high latency $it")
}
In this case, this will only proceed when the latency is more than 20 ie not less than 20, and will chain it further. Also, if the condition is false that means if the latency is less than 20, it will return null so we need to use the safe call or null check.

Reference: Kotlin docs