TExcelTAD
Home › Kotlin › Kotlin Scope Functions

Kotlin Scope Functions

The standard library has five small functions — let, run, with, apply and also — that execute a block of code in the context of an object. They don't add new abilities; they make code more concise and readable. The challenge is choosing the right one, so this chapter focuses on the two differences between them.

The two differences

  1. How the object is referred to inside the block: as it (lambda argument) or as this (receiver — members usable without a prefix).
  2. What the call returns: the lambda result or the object itself.
Function Object is Returns Typical use
let it lambda result null checks (x?.let { }), transforming a value
run this lambda result compute a result from an object's members
with(obj) this lambda result call several functions on an object
apply this the object configure / initialise an object
also it the object side effects: logging, validation

let

let is most often combined with the safe-call operator: the block runs only if the value isn't null.

kotlin · try it yourself
fun main() {
    val input: String? = "  42 "
    val number = input?.let { it.trim().toInt() * 2 }
    println(number)

    val missing: String? = null
    missing?.let { println("never printed") }
    println(missing?.let { it.length } ?: "nothing")
}
84
nothing

apply

apply runs the block with the object as this and returns the object — perfect for configuring something right after creating it:

kotlin · try it yourself
class Email {
    var to = ""
    var subject = ""
    var body = ""
    override fun toString() = "To: $to | $subject | $body"
}

fun main() {
    val mail = Email().apply {
        to = "team@example.com"
        subject = "Release"
        body = "Version 2.0 is live!"
    }
    println(mail)

    val list = mutableListOf(3, 1).apply { add(2); sort() }
    println(list)
}
To: team@example.com | Release | Version 2.0 is live!
[1, 2, 3]

also

also passes the object as it and returns the object — "and also do this". It fits side effects that shouldn't change the flow of a chain:

kotlin · try it yourself
fun main() {
    val result = listOf(5, 3, 8)
        .also { println("Before: $it") }
        .sorted()
        .also { println("After sort: $it") }
        .map { it * 10 }
    println(result)
}
Before: [5, 3, 8]
After sort: [3, 5, 8]
[30, 50, 80]

run and with

run and with both use this and return the block's result. run is called on an object (and works with ?.); with takes the object as an argument.

kotlin · try it yourself
data class Cart(val items: List<Double>, val discount: Double)

fun main() {
    val cart = Cart(listOf(10.0, 25.5, 4.5), 0.1)

    val total = cart.run {
        val sum = items.sum()
        sum - sum * discount
    }
    println("Total: $total")

    val report = with(StringBuilder()) {
        append("Items: ").append(cart.items.size)
        append(", max: ").append(cart.items.max())
        toString()
    }
    println(report)
}
Total: 36.0
Items: 3, max: 25.5

Picking the right one

A quick decision guide:

  • Need to run code only when not null? → ?.let
  • Configuring a new object? → apply
  • Adding a side effect (log, check) in a chain? → also
  • Computing a value from an object's members? → run (or with if not null)
kotlin · try it yourself
data class User(var name: String = "", var age: Int = 0)

fun main() {
    val user = User()
        .apply { name = "Noor"; age = 27 }   // configure
        .also { println("Created $it") }     // log

    val canVote = user.run { age >= 18 }    // compute
    val greeting = user.name.let { "Hello, $it" } // transform
    println("$greeting - can vote: $canVote")
}
Created User(name=Noor, age=27)
Hello, Noor - can vote: true

Tip: Don't nest scope functions deeply or chain too many — it and this quickly become ambiguous. If a block gets long, a normal variable and a few plain statements are clearer.

takeIf { … } and takeUnless { … } are close relatives: they return the object if the condition holds (or doesn't), otherwise null — e.g. input.takeIf { it.isNotBlank() } ?: "default".

Test yourself

Which scope function returns the object itself and uses this inside?

  1. let
  2. run
  3. apply
  4. also

What does "abc".let { it.length } return?

  1. "abc"
  2. 3
  3. Unit
  4. null

Which function is most idiomatic for executing code only when a nullable value is not null?

  1. ?.let { }
  2. with(x) { }
  3. apply { }
  4. also { } without ?.