also: Side Effects Without Changing the Receiver
Use also for logging, debugging, and side-effect-only operations.
also at a Glance
also runs a block with the receiver as it and returns the receiver unchanged. Perfect for side effects — logging, debugging, validation — without disrupting a chain.
Basic also
also { ... } performs a side effect and yields the same value back, so calls flow naturally.
fun main() {
val nums = listOf(1, 2, 3, 4)
.also { println("input: $it") }
.filter { it % 2 == 0 }
.also { println("filtered: $it") }
println(nums)
}All lessons in this course
- apply and with: Configure and Return
- let and run: Transform and Scope
- also: Side Effects Without Changing the Receiver
- Choosing the Right Scope Function: Decision Guide