How to Use the "Also" And "TakeIf" Functions In Kotlin?

9 minutes read

In Kotlin, the "also" and "takeIf" functions are useful for performing additional operations on objects or checking a condition before returning a result.

  1. The "also" function: The "also" function allows you to perform a side effect or additional operation on an object and then return the original object. It is defined as an extension function on any object. The general syntax is as follows:
1
2
3
4
fun <T> T.also(block: (T) -> Unit): T {
    block(this)
    return this
}


You can call the "also" function on any object and provide a lambda expression or a function as the argument. This lambda will be invoked with the object as its receiver, allowing you to perform any desired operations. After executing the lambda, the original object itself is returned.


For example, consider the following code:

1
2
3
val numberList = mutableListOf(1, 2, 3, 4) 
val sum = numberList.also { println(it) } // Print the list and assign it to sum


In this example, the "also" function is used to print the numberList and assign it to the variable sum. The original numberList is returned by the function, allowing further operations if required.

  1. The "takeIf" function: The "takeIf" function is used to check a given condition on an object, and if the condition is true, it returns that object; otherwise, it returns null. It is defined as an extension function on any object. The general syntax is as follows:
1
fun <T> T.takeIf(predicate: (T) -> Boolean): T?


You can call the "takeIf" function on any object and provide a lambda expression or a function as the argument. Inside the lambda, you can specify the condition you want to check. If the condition evaluates to true, the object is returned; otherwise, null is returned.


For example, consider the following code:

1
2
3
val number = 10
val result = number.takeIf { it % 2 == 0 } // Check if the number is even


In this example, the "takeIf" function is used to check if the number is even. Since the number is 10 and it is even, the "takeIf" function returns the number itself. If the number was odd, the function would have returned null.


By using the "also" and "takeIf" functions effectively, you can enhance the readability and flexibility of your code in Kotlin.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.7 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

5
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.6 out of 5

Kotlin Cookbook: A Problem-Focused Approach

6
Java to Kotlin: A Refactoring Guidebook

Rating is 4.5 out of 5

Java to Kotlin: A Refactoring Guidebook

7
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.4 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

8
Advanced Kotlin (Kotlin for Developers Book 4)

Rating is 4.3 out of 5

Advanced Kotlin (Kotlin for Developers Book 4)


How to combine the usage of "also" and "takeIf" functions in Kotlin?

In Kotlin, you can combine the usage of the "also" and "takeIf" functions to perform additional operations and conditionally modify an object. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
data class Person(val name: String, var age: Int)

fun main() {
    val person = Person("John Doe", 25)
    
    val modifiedPerson = person.also { it.age += 1 }
        .takeIf { it.age > 25 }
        ?.also { it.name = "Jane Doe" }
    
    println(modifiedPerson)
}


In the above example, we have a Person class with a name and age property. We first use the also function to increment the age of the person by 1. Then, we use the takeIf function to check if the age is greater than 25. If it is, we use the also function again to modify the name property of the person to "Jane Doe". The final result is stored in the modifiedPerson variable.


Note that the takeIf function returns the receiver object if the condition is true, otherwise null. So, we use the safe-call operator ?. to chain the second also function only if the condition is true.


In this example, if the age is not greater than 25, the modifiedPerson variable will be null.


What is the syntax for using the "also" function in Kotlin?

The also function in Kotlin is an extension function for any object and it takes a lambda function as a parameter. The syntax for using the also function is as follows:

1
2
3
4
object.also { it ->
    // Perform operations on object
    // Return object if needed
}


Here, object refers to the object you want to perform operations on within the lambda function. it is the default name for the object within the lambda, but you can use any name you prefer. You can perform any desired operations on the object within the lambda, and if needed, you can return the modified object from the lambda.


How to chain multiple "takeIf" functions in Kotlin?

To chain multiple takeIf functions in Kotlin, you can simply call takeIf on the result of the previous takeIf function, like so:

1
2
3
4
val result = value
    .takeIf { condition1 }
    .takeIf { condition2 }
    .takeIf { condition3 }


Here, value is the initial value you want to chain takeIf functions on, and condition1, condition2, and condition3 are the conditions that each takeIf function checks.


The takeIf function returns the original value (value) if the condition is true, and null otherwise. So, each subsequent takeIf function is called only if the previous condition is true.


You can continue chaining as many takeIf functions as you need to.


Note that the final result will be null if any of the conditions in the chain are false. If all the conditions are true, the final result will be the original value.


Example usage:

1
2
3
4
5
6
7
8
val value = 10

val result = value
    .takeIf { it > 5 }
    .takeIf { it < 15 }
    .takeIf { it % 2 == 0 }

println(result) // Output: 10


In this example, the result will be 10 because all the conditions (it > 5, it < 15, and it % 2 == 0) are true for the initial value of 10.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

The Kotlin Standard Library functions are a set of utility functions that come built-in with the Kotlin programming language. These functions provide convenient ways to perform common tasks when working with different types of data.To use the Kotlin Standard L...
Kotlin reflection allows you to inspect and manipulate code at runtime. Although Kotlin is fully compatible with Java, accessing Kotlin&#39;s reflection API from Java requires some extra steps.To use Kotlin reflection in Java, you need to follow these steps:Im...
Higher-order functions in Kotlin are a powerful feature that allows you to treat functions as first-class citizens. In other words, you can pass functions as arguments to other functions, return them from functions, or even assign them to variables.To work wit...