0
0
Kotlinprogramming~5 mins

Also function behavior and use cases in Kotlin

Choose your learning style9 modes available
Introduction

The also function helps you run extra actions on an object without changing it. It keeps your code neat and easy to read.

When you want to do something with an object, like logging or printing, without changing it.
When you want to perform side effects during a chain of calls, like modifying a variable or saving data.
When you want to initialize or configure an object and still return the original object.
When you want to debug by printing the value inside a chain of calls without breaking the chain.
Syntax
Kotlin
val result = obj.also {
    // actions using 'it'
}

The also function takes a lambda with the object as it.

It returns the original object after running the lambda.

Examples
This prints the number but result still holds the original number 5.
Kotlin
val number = 5
val result = number.also { println("Number is $it") }
This adds 4 to the list and returns the same list with the new item.
Kotlin
val list = mutableListOf(1, 2, 3)
val newList = list.also { it.add(4) }
This prints "hello" and then converts it to uppercase.
Kotlin
val text = "hello"
val upper = text.also { println(it) }.uppercase()
Sample Program

This program logs the name using also and then prints the original name stored in result.

Kotlin
fun main() {
    val name = "Alice"
    val result = name.also {
        println("Logging name: $it")
    }
    println("Result is: $result")
}
OutputSuccess
Important Notes

also is useful for side effects like logging or modifying mutable objects.

It does not change the original object reference returned.

Use also when you want to keep the object but do extra work with it.

Summary

also runs extra code on an object and returns the original object.

Great for logging, debugging, or modifying mutable objects without breaking chains.

Helps keep code clean and readable by separating side effects.