Careeroza
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).
| Function | Object is | Returns | Typical use |
|---|---|---|---|
let | it | lambda result | null checks, transform a value |
run | this | lambda result | configure + compute a result |
with | this (argument) | lambda result | group calls on one object |
apply | this | the object | build / configure an object |
also | it | the object | side 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