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>()
}
Create a free account and build your private vault. Share publicly whenever you want.