‘takeIf’ and ‘takeUnless’ : Kotlin

Suneet Agrawal
2 min readMay 10, 2019

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?

This post was originally posted at https://agrawalsuneet.github.io/blogs/takeif-and-takeunless-kotlin/ and reposted on Medium on 10th Mar 2019.

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.

takeIf is a filtering function for a single object whereas takeUnless is a counter of takeIf.

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.

Please continue reading at https://agrawalsuneet.github.io/blogs/takeif-and-takeunless-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Reference: Kotlin docs

--

--