also
The Kotlin scope function also is used to insert side effects — such as logging, debugging, or additional processing — on an object. Inside the block, the object is referenced as it, and the return value is the receiver itself.
Syntax
// Basic form of also
val result = object.also {
// it = the object
println(it) // side effect (e.g., logging)
}
// result is the object itself
Syntax Overview
| Scope Function | Context Reference | Return Value | Use Case |
|---|---|---|---|
| also { } | it | Receiver itself | Used to insert side effects such as logging or debugging. |
| apply { } | this (can be omitted) | Receiver itself | Used for object configuration and initialization. |
| let { } | it | Lambda result | Used for null checks and transformation chains. |
| run { } | this (can be omitted) | Lambda result | Combines object setup with computation. |
Sample Code
fun main() {
// Use also to insert a log in the middle of a method chain.
val numbers = mutableListOf(1, 2, 3)
.also { println("Before transform: $it") } // Before transform: [1, 2, 3]
.map { it * 2 }
.also { println("After transform: $it") } // After transform: [2, 4, 6]
println(numbers) // [2, 4, 6]
// also returns the receiver, so you can add logging without interrupting the chain.
val text = "Hello, Kotlin!"
.also { println("Length: ${it.length}") } // Length: 14
.uppercase()
println(text) // HELLO, KOTLIN!
// also can also be used to insert validation.
data class User(val name: String, val age: Int)
fun createUser(name: String, age: Int): User {
return User(name, age).also {
require(it.age >= 0) { "Age must be 0 or greater" }
println("User created: $it")
}
}
val user = createUser("Bob", 25)
println(user)
// User created: User(name=Bob, age=25)
// User(name=Bob, age=25)
}
Overview
The key feature of also is that it lets you add side effects without changing the flow of your code. It is particularly useful for inserting debug logs or adding validation in the middle of a method chain.
Both also and apply return the receiver itself, but they differ in how they reference the context: also uses it, while apply uses this. Use also when operating on the object from the outside, and apply when configuring the object itself.
See apply for object initialization, and let for null checks.
If you find any errors or copyright issues, please contact us.