run()
Some of the other scope functions simply remix features of apply()
and let()
a bit differently. run()
, for example, works a bit like apply()
, in that whatever you call run()
on becomes this
in the scope of the lambda expression that you supply. However, run()
also works a bit like let()
, in that the result of run
is whatever the last statement of the lambda expression returns.
run
is useful when you want to call a bunch of functions on some object, but then the end result is not the object itself, but something else… such as the result of one of those functions:
data class IntPropertyBag(private val pieces: MutableMap<String, Int> = mutableMapOf()) {
fun set(key: String, value: Int) {
pieces[key] = value
}
}
fun main() {
val ultimateStuff = IntPropertyBag().run {
set("ID", 330258648)
set("YEAR", 1979)
set("HOW_MANY_ROADS_MUST_A_MAN_WALK_DOWN", 42)
toString()
}
println(ultimateStuff)
}
Here, we call run()
on a IntPropertyBag
instance, just as we did with apply()
in the previous section. However, ultimateStuff
is not the IntPropertyBag
object, but instead the result of toString()
called on the IntPropertyBag
object. In the context of println()
, there is no practical difference, as println()
will call toString()
to generate what to print. However, in other situations, the value that you generate from the run
lambda expression might be more distinctly different.
In summary, run()
:
- Is called on some object
- Takes whatever you call it on and makes it be the “current” object —
this
— in the scope of the lambda expression - Returns whatever the last statement of the lambda expression evaluates to
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.