Overview
There are two different run()
functions defined in Standard.kt in the Kotlin standard library, among a handful of scope functions that are frequently used in Kotlin programming. This article describes the one that’s an extension function.
Example
val size = "Hello".run {
println(this)
this.length
}
In this example, the string “Hello” is printed, and then its length is assigned to the size
variable.
Characteristics
When the run()
extension function executes:
- the receiver object that
.run()
is called upon is available asthis
- the result of
run()
will be the result of the code block passed to it
Initialize and Execute
A good use case for the run()
extension function is initializing an object that is immediately executed, or passed to something else for execution. Here’s an example using a hypothetical HTTP client:
val response = Request("GET", "https://www.example.com/").run {
addQueryParam("name1", "value1")
addQueryParam("name2", "value2")
execute()
}
In this example, the Request
object is built up with additional query params before calling execute()
on it. The code here has no further use for the Request
object after it’s executed, so it’s never actually assigned to anything - response
will contain the result of Request.execute()
.
Alternatives
The guide, Understanding Kotlin’s let(), also(), run(), and apply() has some information about how to choose which scope function to use.