Kotlin Cheatsheet: Scope Functions (let, run, apply, also, with)
Nov 6 · 1 min read

Note: this can be omitted.
There are recommended use-cases for each scope function but at the end of the day, choose the function that returns you the correct output and fits your code convention.
apply
Useful for:
- configuring an object:
val foo = Foo().apply {
this.field1 = 1
}run
Useful for:
- configuring an object and computing the result:
val bar = Foo().run {
this.field1 = 1
this.toBar()
}- grouping several statements into an expression:
runhas a non-extension form too:
val bar = run {
val foo = Foo()
foo.field1 = 1
foo.toBar()
}also
Useful for:
- doing additional effects involving the object:
val foo = Foo().also {
doSomethingTo(it)
}let
Useful for
- executing a lambda on non-null objects:
val bar = getFoo()?.let {
it.toBar()
}- introducing an expression as a variable in local scope:
(...complicated expression...).let {
doSomethingWith(it)
}with
Useful for:
- grouping function calls on an object. Similar to
runbut not an extension:
val bar = with(Foo()) {
this.field1 = 1
this.toBar()
}
