Kotlin scope functions let
, apply
, also
, run
look like asynchronous callbacks. But they seem to be executed sequentially. How is this done? What are the implementation details?
CodePudding user response:
Scope functions are just meant to make your code easier to read and write. They are not asynchronous callbacks.
The scope functions do not introduce any new technical capabilities, but they can make your code more concise and readable.
In fact, they are inline functions. For example, apply
is declared like this:
// Note "inline" modifier
public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
inline
functions are inlined to their call site. For example, this code from the documentation:
val adam = Person("Adam").apply {
age = 20
city = "London"
}
println(adam)
gets turned into something like this during compilation - the apply
call is completely eliminated
val temp = Person("Adam")
temp.age = 20
temp.city = "London"
val adam = temp
println(adam)