Using Kotlin takeIf (or takeUnless)

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

  1. It is called from the T object itself. i.e. T.takeIf.
  2. The predicate function takes T object as parameter
  3. It returns this or null pending on the predicate evaluation.

Appropriate use

Based on the characteristics above, I could derive it’s usage as oppose to if condition in the below scenarios.

1. It is called from the T object…

--

--