Kotlin takeIf and takeUnless: Conditional Expression Functions

beginner
11 min

Kotlin takeIf and takeUnless: Conditional Expression Functions

Welcome, programmers! Today, we're diving into the world of Kotlin's conditional expression functions: takeIf and takeUnless. Let's get started!

Introduction 🎯

takeIf and takeUnless are functions in Kotlin that allow you to conditionally modify a collection based on a given condition. They help you avoid using complex if-else blocks and make your code more readable and concise.

takeIf 💡

takeIf is a function that takes a condition as a parameter and returns the collection if the condition is true, otherwise an empty collection.

Syntax 📝

kotlin
takeIf { condition }: T. () -> T

Example ✅

Let's consider a simple example where we have a list of numbers and we want to filter out any numbers greater than 10.

kotlin
val numbers = listOf(5, 12, 8, 15, 7, 18) val filteredNumbers = numbers.takeIf { it > 10 } println(filteredNumbers) // Output: [12, 15, 18]

In this example, we've defined a list of numbers and used takeIf to filter out the numbers greater than 10. The filtered numbers are then printed to the console.

takeUnless 💡

takeUnless is a function that works similar to takeIf, but it returns the collection if the condition is false, otherwise an empty collection.

Syntax 📝

kotlin
takeUnless { condition }: T. () -> T

Example ✅

Continuing with our previous example, let's now filter out the numbers less than or equal to 10 using takeUnless.

kotlin
val numbers = listOf(5, 12, 8, 15, 7, 18) val filteredNumbers = numbers.takeUnless { it <= 10 } println(filteredNumbers) // Output: [5, 12, 15, 18]

In this example, we've used takeUnless to filter out the numbers less than or equal to 10. The filtered numbers are then printed to the console.

Quiz 📝

Quick Quiz
Question 1 of 1

Which function returns the collection if the condition is true?

Quick Quiz
Question 1 of 1

Which function returns the collection if the condition is false?

That's it for today! We've covered the basics of Kotlin's takeIf and takeUnless functions. These functions can greatly simplify your conditional logic and make your code more readable. Keep practicing and happy coding! 🚀