also

Side Effects Without Breaking the Chain

also receives the object as it and returns the object unchanged. Read it as "and also do this": log, validate, or save, in the middle of a chain.

Example

fun main() {
    val result = listOf(4, 9, 1, 7)
        .also { println("Original: $it") }
        .sorted()
        .also { println("Sorted:   $it") }
        .map { it * 10 }
    println("Result:   $result")

    var lastId = 100
    fun nextId() = (lastId + 1).also { lastId = it }
    println(nextId()); println(nextId())
}

Output

Original: [4, 9, 1, 7]
Sorted:   [1, 4, 7, 9]
Result:   [10, 40, 70, 90]
101
102