Also
Single-expression functions are very nice and concise:
fun multiply(a: Int, b: Int): Int = a * b
But often, you have a single-statement function, that also needs to write to a log, for example.
You could write it the following way:
fun multiply(a: Int, b: Int): Int { val c = a * b println(c) return c }
But then it's not a single statement function anymore, right?
And we also introduced another variable. To the rescue, also()
:
fun multiply(a: Int, b: Int): Int = (a * b).also { println(it) }
This function will set results of the expression to it
and return the result of the expression.
This is also useful when you want to have a side effect on a chain of calls:
val l = (1..100).toList() l.filter{ it % 2 == 0 } .also { println(it) } // Prints, but doesn't change anything .map { it * it }