Using Kotlin takeIf (or takeUnless)
Published in
3 min readNov 28, 2017
In Kotlin’s standard functions, there’s two function i.e. takeIf
and takeUnless
, that at first glance, what’s so special about it? Is it pretty much just if
?
Or one could go the extreme, replace every if
it sees as below (NOT recommended).
// Original Code
if (status) { doThis() }// Modified Code
takeIf { status }?.apply { doThis() }
Under the hood
Like any other thing, takeIf
(or takeUnless
) do have its’ place of use. I share my view of them in the various scenario. Before we proceed, let’s look at the implementation of it.
The implementation signature
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T?
= if (predicate(this)) this else null
From it, we notice that
- It is called from the T object itself. i.e.
T.takeIf
. - The
predicate
function takes T object as parameter - It returns
this
ornull
pending on thepredicate
evaluation.
Appropriate use
Based on the characteristics above, I could derive it’s usage as oppose to if
condition in the below scenarios.