Kotlin also()

Kotlin also()

The also() function in Kotlin is used for additional actions on an object and returns the original object.

It allows you to perform additional operations within a block and retain the original object, typically used for side effects.

In this tutorial, we shall learn the syntax and go through some examples of Kotlin also() function.

Syntax

The syntax of the also() function is:

inline fun <T> T.also(block: (T) -> Unit): T

where

ParameterDescription
blockThe lambda block to be executed on the object.
Parameter of also() function

The function takes a lambda block that operates on the object of type T and returns the original object after performing the block’s operations.

Examples

1. Using also() for Additional Operations

In this example, we’ll use also() to perform additional operations on a string, say like printing the length of the string.

Kotlin Program

fun main() {
    val originalString = "Hello, Kotlin!"

    val modifiedString = originalString.uppercase().also {
        // Perform additional operations
        println("String length : ${it.length}")
    }

    // Display the original and modified strings
    println("Original String: $originalString")
    println("Modified String: $modifiedString")
}

Output

String length : 14
Original String: Hello, Kotlin!
Modified String: HELLO, KOTLIN!

In this example, also() is used to perform additional operations within the block, and the original string is retained for further use.

Summary

The also() function in Kotlin is a versatile utility for performing additional operations on an object while preserving the original object.

It is commonly used for side effects within fluent and concise code.