Scope Functions Overview

Five Functions, Two Questions

Scope functions run a block of code on an object. They differ in only two ways: how the block refers to the object (this or it) and what the call returns (the object itself, or the lambda result).

FunctionObject isReturnsTypical use
letitlambda resultnull checks, transform a value
runthislambda resultconfigure + compute a result
withthis (argument)lambda resultgroup calls on one object
applythisthe objectbuild / configure an object
alsoitthe objectside effects: logging, validation

All Five Side by Side

Example

data class Person(var name: String, var age: Int = 0)

fun main() {
    val p = Person("Asha")

    val a = p.let { it.name.length }          // it, returns result
    val b = p.run { "$name is $age" }         // this, returns result
    val c = with(p) { name.uppercase() }      // this, returns result
    val d = p.apply { age = 25 }              // this, returns p
    val e = p.also { println("Logging: $it") } // it, returns p

    println(a); println(b); println(c); println(d); println(e === p)
}

Output

Logging: Person(name=Asha, age=25)
4
Asha is 0
ASHA
Person(name=Asha, age=25)
true