0
0
KotlinHow-ToBeginner · 3 min read

How to Use also Function in Kotlin: Simple Guide

In Kotlin, the also function lets you run extra code on an object and then returns the same object. It is useful for performing side effects like logging or debugging without changing the original object.
📐

Syntax

The also function is called on an object and takes a lambda with the object as its argument. It returns the original object after executing the lambda.

  • receiver.also { it -> /* code using it */ }
  • it refers to the object inside the lambda.
  • The original receiver is returned unchanged.
kotlin
val result = obj.also { it ->
    // code using it
}
// result is the same as obj
💻

Example

This example shows how to use also to print a message about a string while keeping the string unchanged.

kotlin
fun main() {
    val name = "Kotlin"
    val result = name.also {
        println("The original string is: $it")
    }
    println("Result after also: $result")
}
Output
The original string is: Kotlin Result after also: Kotlin
⚠️

Common Pitfalls

One common mistake is to expect also to return a modified object or a different value. It always returns the original object unchanged.

Another mistake is confusing also with apply or let, which have different behaviors.

kotlin
fun main() {
    val list = mutableListOf(1, 2, 3)

    // Modifies the list but also returns the original list
    val modified = list.also {
        it.add(4)
    }
    println(modified) // prints [1, 2, 3, 4]

    // Using also for side effect without modifying
    val sideEffect = list.also {
        println("Added 4 to list")
    }
    println(sideEffect) // prints [1, 2, 3, 4]
}
Output
Added 4 to list [1, 2, 3, 4]
📊

Quick Reference

  • Purpose: Perform side effects on an object without changing it.
  • Returns: The original object.
  • Use case: Logging, debugging, or chaining calls.
  • Difference from apply: apply returns the object but uses this inside lambda; also uses it.

Key Takeaways

The also function runs code on an object and returns the same object unchanged.
Use also for side effects like logging or debugging without modifying the object.
Inside also's lambda, the object is referenced as it.
also differs from apply by using it instead of this and focusing on side effects.
Expect also to return the original object, not a transformed one.