Kotlin example

How to use scope functions in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Pick by what you want back. obj.apply { … } and obj.also { … } return the object itself: use apply to set it up (inside, the object is this) and also for side effects such as logging (the object is it). let, run and with return the block's last expression: let (it) to transform a value or, as x?.let { … }, to act only when it is not null; run and with (this) to compute something from an object's members.

The five scope functions, let, run, with, apply and also, all do the same basic thing: run a block of code with an object in reach. They differ in two ways only: whether the block sees the object as this (so you write width) or as it (so you write it.width), and whether the call returns the object or the block's result. Java has no counterpart; in Kotlin, apply replaces a run of setter calls or a builder, and ?.let replaces a temporary variable plus if (x != null). The sections below show all five side by side, each pair in detail, takeIf and takeUnless, and the mistakes people make, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1All five at a glance: this or it, object or resultRecommended

The program below runs all five on the same kind of object. Read each call with two questions in mind. Inside the block, is the object it (let, also) or this (run, with, apply)? And what comes back: the block's last expression (let, run, with) or the object itself (apply, also)? with is the odd one out in how you call it: it is a plain function that takes the object as its first argument, with(box) { … }, while the other four are extension functions you call on the object.

AllFive.kt
data class Box(var width: Int = 0, var height: Int = 0)

fun main() {
    val box = Box(3, 4)

    // let: the object is it, the block's result comes back
    val a = box.let { it.width * it.height }
    // run: the object is this, the block's result comes back
    val b = box.run { width * height }
    // with: like run, but the object goes in as an argument
    val c = with(box) { width * height }
    println("let=$a run=$b with=$c")

    // apply: the object is this, the object itself comes back
    val d = Box().apply {
        width = 5
        height = 6
    }
    // also: the object is it, the object itself comes back
    val e = Box(7, 8).also { println("made $it") }
    println("apply=$d also=$e")

    // The same block, two different results
    println(box.run { width + 1 })
    println(box.apply { width + 1 })
}

Output

let, run and with all give 12, the area the block computed; only the spelling differs (it.width against width). apply and also give the boxes themselves, printed as Box(width=5, height=6) and Box(width=7, height=8), and the also block ran first, which is why made Box(width=7, height=8) comes before them. The last two lines run the same block { width + 1 }: run returns 4, apply throws that away and returns the unchanged box.

2apply and also: return the object

Both return the object they were called on, so both fit in the middle of an expression or a call chain. apply gives you the object as this, so you write port = 443 instead of conn.port = 443: use it to configure an object right where you create it. also gives you the object as it: use it for things you do with the object rather than to it, such as logging, a check or adding it to a list. That is the whole answer to "apply vs also": same result, and the choice is whether the block reads better with this or with it.

ApplyAlso.kt
class Connection {
    var host = "localhost"
    var port = 80
    var secure = false

    override fun toString() = "Connection($host:$port, secure=$secure)"
}

fun main() {
    // apply: set properties on a new object, get the object back
    val conn = Connection().apply {
        host = "example.com"
        port = 443
        secure = true
    }
    println(conn)

    // also: do something extra with the object, then pass it on
    val sorted = mutableListOf(3, 1, 2)
        .also { println("before: $it") }
        .apply { sort() }
        .also { println("after: $it") }
    println("size ${sorted.size}")

    // also when a name would clash with a property: it stays explicit
    val port = 8080
    val local = Connection().also { it.port = port }
    println(local)

    // The swap idiom: also runs after b's old value is read
    var a = 1
    var b = 2
    a = b.also { b = a }
    println("a=$a b=$b")
}

Output

The apply block sets three properties and the result prints as Connection(example.com:443, secure=true). In the chain, each also logs the list without changing it, and apply sorts it in place: before: [3, 1, 2], then after: [1, 2, 3]. With a local port in scope, apply { port = port } would not even compile (here it stops with 'val' cannot be reassigned., because the local name wins over the property); also { it.port = port } says which is which. The last line is a known Kotlin idiom: a = b.also { b = a } swaps two variables, giving a=2 b=1.

3let and ?.let: transform a value or skip null

x.let { … } passes the value in as it and returns whatever the block returns, so it turns one value into another at the end of an expression, where there is no variable to work with. Its most common use is with a safe call: x?.let { … } runs the block only when x is not null, and adding ?: default gives one non-null result. Give the parameter a name (sum -> …) when it would be unclear, and use let to keep a temporary value from leaking into the rest of the function. The full null story, with smart casts and !!, is in check for null.

LetTransform.kt
fun main() {
    // let: turn a value into something else
    val words = "  scope functions in kotlin  ".let { it.trim().split(" ") }
    println(words)

    // ?.let: run the block only when the value is not null
    val env = mapOf("PORT" to "8080")
    env["PORT"]?.let { println("port is $it") }
    env["HOST"]?.let { println("host is $it") }

    // ?.let with a fallback gives one non-null value
    val host = env["HOST"]?.let { "host $it" } ?: "host not set"
    println(host)

    // Name the parameter when it would be unclear
    val total = listOf(4, 8, 15).sum().let { sum -> "total: $sum" }
    println(total)

    // let keeps a temporary out of the outer scope
    val area = (1920 to 1080).let { (w, h) -> w * h }
    println("area $area")
}

Output

The first let trims and splits in one expression: [scope, functions, in, kotlin]. The map has a PORT but no HOST, so port is 8080 prints and the second block is skipped without a sound; with the Elvis fallback the missing key becomes host not set. The last let destructures the pair into w and h, which exist only inside the block, and prints area 2073600.

4run and with: compute a result with this

run and with both give you the object as this and return the block's last expression. Use with(obj) { … } when you already have the object and want several of its members without repeating its name. obj.run { … } does the same as an extension, so it chains and works after a safe call: obj?.run { … }; with takes a nullable argument as is, so every member call inside would need ?.. apply vs with comes down to the result: apply returns the object, with returns what the block computed. There is also a run with no receiver at all, a block that runs once and gives a value, handy where Kotlin expects one expression.

RunWith.kt
class Account(val owner: String, var balance: Int)

fun main() {
    val account = Account("Ada", 100)

    // with: you already have the object; the last line is the result
    val report = with(account) {
        balance += 50
        "$owner has $balance"
    }
    println(report)

    // run: the same, called on the object, so it chains and works with ?.
    val doubled = account.run { balance * 2 }
    println("doubled: $doubled")
    val nobody: Account? = null
    println(nobody?.run { "$owner has $balance" } ?: "no account")

    // apply vs with: the object back, or the block's result
    val fromApply = StringBuilder("ab").apply { append("c") }
    val fromWith = with(StringBuilder("ab")) {
        append("c")
        length
    }
    println("apply gave $fromApply, with gave $fromWith")

    // run without a receiver: a block that computes one value
    val greeting = run {
        val first = "Ada"
        val last = "Lovelace"
        "Hello, $first $last"
    }
    println(greeting)
}

Output

The with block changes the balance and returns the string, Ada has 150; run reads the new balance and gives doubled: 300. On the null account, ?.run skips the block and the Elvis prints no account. The two builders get the same append, but apply returns the builder (it prints as abc) and with returns the last line, its length 3. The plain run block keeps first and last local and gives Hello, Ada Lovelace.

5takeIf and takeUnless: keep a value or get null

Two smaller functions from the same family filter a single value. x.takeIf { test } returns x when the test passes and null when it fails; takeUnless does the opposite. The result is nullable, so you follow it with ?: for a default or ?.let to act on the values that pass. Together they replace a small if/else around a value, such as "use this number if it is in range, else 20".

TakeIf.kt
fun pageSize(text: String): Int =
    text.toIntOrNull()?.takeIf { it in 1..100 } ?: 20

fun main() {
    // takeIf: the value when the test passes, null when it fails
    println("kotlin".takeIf { it.length > 3 })
    println("go".takeIf { it.length > 3 })

    // takeUnless: the opposite test
    val name = "   ".takeUnless { it.isBlank() } ?: "guest"
    println("name: $name")

    // With ?: they replace a small if/else around a value
    for (input in listOf("50", "500", "abc")) {
        println("$input -> ${pageSize(input)}")
    }

    // With ?.let they act only on the values that pass
    val files = listOf("notes.txt", "photo.png", "todo.txt")
    for (file in files) {
        file.takeIf { it.endsWith(".txt") }?.let { println("open $it") }
    }
}

Output

"go" fails the length test and prints null. The blank string is blank, so takeUnless drops it and the Elvis gives name: guest. In pageSize, "500" is a number but out of range and "abc" is not a number at all; both end at the default 20. Only the two .txt files reach the let. The block of takeIf is a test, so keep it free of side effects, and remember the ?. after it: the result can be null.

6Common mistakes with scope functions

Scope functions are easy to write and easy to misread. Four mistakes come up again and again: expecting apply to return what the block computed; nesting two lambdas that both use it, so the inner one hides the outer; assigning to a name inside apply that is also a local variable, which sets the variable and not the property; and using x?.let { … } ?: run { … } as an if/else. All four compile and run; the output is where they show.

ScopeMistakes.kt
class Button {
    var label = "Button"
}

fun main() {
    // 1. apply gives back the object, not what the block computed
    println("kotlin".apply { uppercase() })
    println("kotlin".run { uppercase() })

    // 2. Nested lambdas: the inner it hides the outer one
    val first: String? = "Ada"
    val last: String? = "Lovelace"
    first?.let { last?.let { println("$it $it") } }
    first?.let { f -> last?.let { l -> println("$f $l") } }

    // 3. Inside apply, a local variable wins over the object's property
    var label = "draft"
    val ok = Button().apply { label = "OK" }
    println("button: ${ok.label}, local: $label")
    val fixed = Button().apply { this.label = "OK" }
    println("button: ${fixed.label}")

    // 4. ?.let { } ?: run { } is not if/else
    val names = mapOf("ada" to "Ada Lovelace")
    val id: String? = "linus"
    id?.let { names[it]?.let(::println) } ?: run { println("id is null?") }
}

Output

1: apply { uppercase() } prints kotlin, because the new string is thrown away; run returns it, KOTLIN. 2: the inner it is last both times, so the first name is lost and the line reads Lovelace Lovelace; naming the parameters fixes it. 3: the button keeps its default, button: Button, local: OK, because label inside the block meant the local var; write this.label, or rename the local. 4: id is "linus", but the lookup inside the let returns null, so the Elvis runs the other branch and prints id is null?. Use if (id != null) … else … for a real if/else. The general rule: one level of scope function reads well, two need named parameters, and beyond that a plain local val is clearer.

7Which should you use?

FunctionObject isReturnsBest for
obj.apply { … }thisThe objectSetting up a new object
obj.also { … }itThe objectSide effects in a chain: logging, checks
obj?.let { … }itBlock resultNull checks, turning a value into another
obj.run { … }thisBlock resultComputing from members, also after ?.
with(obj) { … }thisBlock resultSeveral calls on an object you already have
run { … }No objectBlock resultA few statements where one expression is expected
obj.takeIf { … }itThe object or nullKeeping a value only if it passes a test

Frequently asked questions

What is the difference between apply and also in Kotlin?

Both return the object they are called on. Inside apply the object is this, so you write port = 443; inside also it is it, so you write it.port = 443. Use apply to configure an object and also for side effects such as logging or validation, where an explicit it reads better and cannot clash with a local name.

What is the difference between apply and with in Kotlin?

Both give you the object as this. apply is an extension (obj.apply { … }) and returns the object; with is a plain function (with(obj) { … }) and returns the block's last expression. So StringBuilder("ab").apply { append("c") } gives the builder, and with(StringBuilder("ab")) { append("c"); length } gives 3.

What is the difference between let and run?

Both return the block's result. In let the object is the parameter it (or a name you choose), in run it is the receiver this, so members are called without a prefix. Pick let when you pass the value to other functions, run when you mostly call its own members.

When should I use with instead of run?

Use with(obj) { … } for a non-null object you already hold in a variable, to group several calls on it. Use obj?.run { … } when the object may be null or sits at the end of a call chain: with cannot be combined with a safe call.

How do I return from inside let, run or apply?

A bare return inside the block returns from the enclosing function, because the scope functions are inline. To leave only the block, use a label: val x = "abc".let { if (it.length < 5) return@let "short"; "long" } gives short.

Do scope functions make code slower?

No. let, run, with, apply, also, takeIf and takeUnless are inline functions, so the compiler copies the block into the call site and no lambda object is created. The cost is readability, not speed: nested scope functions with it and this everywhere are the thing to avoid.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground