Kotlin Tutorial · Functional Kotlin and Collections · Lesson 22 of 31
Kotlin Scope Functions: let, run, apply, also, with
Use let, run, apply, also and with to work with an object inside a block, and know which one to pick.
The five scope functions
| Function | Object inside as | Returns | Typical use |
|---|---|---|---|
let |
it |
lambda result | null checks, transforming a value |
run |
this |
lambda result | compute something from an object |
apply |
this |
the object | configuring an object |
also |
it |
the object | side effects such as logging |
with(obj) |
this |
lambda result | several calls on one object |
class Request {
var url = ""
var method = "GET"
val headers = mutableMapOf<String, String>()
}
fun main() {
val request = Request().apply { // configure, return the object
url = "https://api.example.com/orders"
method = "POST"
headers["Accept"] = "application/json"
}.also { println("built ${it.method} ${it.url}") }
val headerCount = request.run { headers.size } // compute from the object
println(headerCount)
val email: String? = "[email protected]"
val domain = email?.let { it.substringAfter("@") } ?: "unknown"
println(domain)
val summary = with(request) { "$method ${url.substringAfterLast('/')}" }
println(summary)
}
Output
built POST https://api.example.com/orders 1 example.com POST orders
Run this on your computer — see “Get Started” for setup.
Don't nest them deeply: a named variable is often clearer.
Test yourself
Which scope function returns the object itself and exposes it as this?
letrunapplyalso
Show answer
Answer: apply