Skip to content
DeveloperMemos

Kotlin's takeIf and takeUnless in Action

Kotlin, Programming, Android Development1 min read

In Kotlin, the standard library provides a couple of handy extension functions called takeIf and takeUnless. These functions allow you to perform conditional checks in a concise and expressive way. Whether you're working on an Android project or any other Kotlin-based application, understanding how to leverage these functions can greatly enhance your code. In this article, we'll explore the power of takeIf and takeUnless with practical examples.

The takeIf Function

The takeIf function is a simple yet powerful tool for performing conditional checks. It takes a predicate as an argument and returns the receiver object if the predicate is true, or null otherwise. Here's a basic example:

1val number: Int? = 42
2val result = number.takeIf { it > 0 }

In this example, result will be assigned the value of number (which is 42) since the condition it > 0 is true. If the condition were false, result would be null.

One useful application of takeIf is chaining it with other functions. Consider the following scenario where we want to validate a user input:

1fun isValidInput(input: String): Boolean {
2 return input.length >= 8
3}
4
5val userInput: String = getUserInput() // hypothetical function to get user input
6
7val isValid = userInput.takeIf(::isValidInput)?.let { saveData(it) }

Here, isValidInput is a function that checks if the user input has a length of at least 8 characters. By using takeIf, we can conditionally save the valid user input using the saveData function only if the input passes the validation.

The takeUnless Function

The takeUnless function is the inverse of takeIf. It returns the receiver object if the predicate is false, or null otherwise. Let's consider an example:

1val number: Int? = 42
2val result = number.takeUnless { it == null }

In this case, result will be assigned the value of number (which is 42) because the condition it == null is false. If the condition were true, result would be null.

Similar to takeIf, you can chain takeUnless with other functions to perform more complex operations. For instance, suppose you want to calculate the sum of all odd numbers in a list until you encounter a negative number:

1val numbers = listOf(1, 3, 5, -2, 7, 9)
2val sum = numbers.takeUnless { it.contains(-1) }?.filter { it % 2 != 0 }?.sum()

In this example, sum will be calculated as 16 because takeUnless stops the execution and returns null when it encounters the negative number (-2), preventing any further operations on the list.

In Closing

Kotlin's takeIf and takeUnless functions provide elegant ways to conditionally manipulate data and simplify your code. By leveraging these functions, you can enhance the readability and expressiveness of your Kotlin code. Whether you're performing simple validations or implementing more complex logic, takeIf and takeUnless are powerful tools at your disposal.