Kotlin

also — Side Effect, Return Itself

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`x.also { ... }` runs a side-effect block with `x` as `it` and returns `x` unchanged. Used for logging, debugging, or asserting mid-chain without breaking it.
Kotlin
Raw
fun main() {
    // Log a computed value mid-chain without losing it
    val nums = listOf(3, 1, 4, 1, 5, 9, 2, 6)
        .filter { it > 2 }
        .also  { println("after filter: $it") }      // [3, 4, 5, 9, 6]
        .map   { it * it }
        .also  { println("after map: $it") }         // [9, 16, 25, 81, 36]
        .sum()
    println("total: $nums")

    // Common in builders — apply does config, also does side-effects
    val request = HttpRequest("https://example.com")
        .apply { headers["Accept"] = "application/json" }
        .also  { println("created request to ${it.url}") }
}

class HttpRequest(val url: String) {
    val headers = mutableMapOf<String, String>()
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.