Scope functions

Hari Prasad
2 min readJul 10, 2023

--

Scope functions execute a block of code within the context of / on an object.

We have different Scope functions let, with, run, apply, and also

The difference between them is how this object becomes available inside the block and what is the result of the whole expression.

Forms a temporary scope. In that scope, you can access the object without its name.

let - public inline fun <T, R> T.let(block: (T) -> R): R { return block(this)}
run - public inline fun <T, R> T.run(block: (T) -> R): R { return block(this)}
(and) public inline fun <R> run(block: T.() -> R): R { return block()}
apply -public inline fun <T> T.apply(block: T.() -> Unit): { return this}
also - public inline fun <T> T.also(block: (T) -> Unit): T { return this}
with - public inline fun <T, R> with(receiver: T, block: (T) -> R): R { return receiver.block()}
  • let — on non-null object
  • run — multiple operations without name
  • apply — configure an object
  • also — additional operations on object
  • with — multiple operations without name
  • all are inline Functions
  • all are Higher-order Functions
  • except with others are Extension Functions
  • returns
    let, run, with - result
    apply, also - itself
  • context
    let,
    also - it
    run, with, apply - this
data class Person(var name: String, var age: Int)

fun main() {
val person = Person("John", 25)

val modifiedPersonApply = person.apply {
age = 30
}

val modifiedPersonAlso = person.also {
it.age = 35
}

println(modifiedPersonApply) // Output: Person(name=John, age=30)
println(modifiedPersonAlso) // Output: Person(name=John, age=35)
}

--

--