Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 134 ยท Functions

Scope Functions

Learn Kotlin scope functions let, run, with, apply and also - how they differ in receiver and result, when to pick each, takeIf, nesting pitfalls and idiomatic examples with runnable code.

Kotlin's standard library contains five tiny functions that run a block of code inside the context of an object: let, run, with, apply and also. They are called scope functions because the lambda you pass creates a small scope in which the object is available without repeating its name. They do not add new abilities, you could write everything without them, but used well they remove temporary variables, keep configuration code together and make null handling concise.

The five look alike, and beginners often pick one at random. This lesson gives you a simple way to choose: every scope function answers two questions. How do I refer to the object inside the block (as this or as it)? And what does the whole call return (the lambda's result or the object itself)? Once those two questions are clear, the names stop being confusing. The lesson builds on Lambdas, Extension Functions and Null Safety.

The two questions

Function Object inside is Returns Typical use
let it lambda result transform a value, null handling
run this lambda result compute something using the object
with(obj) this lambda result several calls on one object
apply this the object configure an object
also it the object side effects such as logging

this versus it is about style: with this you can call members directly (length, append(...)), with it you write it.length, which makes it obvious where things come from. The return value decides how you chain: a function that returns the object lets you continue using the object; one that returns the lambda result gives you a new value.

let: transform a value

let passes the object as it (or a name you choose) and returns whatever the lambda returns. It shines with nullable values, where ?.let { ... } runs the block only when the value is not null:

Kotlin let for transformations and null checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is KOTLIN, null and 10. missing?.let { ... } is skipped entirely, because the safe-call operator stops when the receiver is null. Inside the block, it has the non-null type String, which is the main reason ?.let is popular. "scope".let { text -> ... } shows a named parameter.

let also limits the scope of a temporary value. Instead of a variable that lives for the whole function, the value exists only inside the block:

Kotlin let to narrow a variable's lifetime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see evens: [4, 8, 16, 42] and count: 4. Here let gives the intermediate result a name without leaking a variable into the rest of the function.

run and with: compute with the object as this

run is like let, but the object is this, so you can call its members without a prefix. It returns the lambda's result. with is the same idea written as a plain function call instead of an extension: with(obj) { ... }.

Kotlin run and with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints Ada has 175, Owner: Ada, balance: 175 and 42. The third use, run { ... } without any receiver, is a way to turn several statements into a single expression, such as when you initialize a val with a block of code. Use with when you already hold a non-null object and want to work with it for a few lines. Use run when the object might be null (obj?.run { ... }) or when you want to chain after other calls.

apply: configure and return the object

apply runs a block with the object as this and then returns the same object. This makes it perfect for initialization, where you create an object and set several properties in one expression:

Kotlin apply for configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is example.org:8443 [secure, primary], one, two, three and [1, 2]. Without apply you would repeat server.host = ...; server.port = ... and need a variable name for every line. Notice that the block's own last expression is ignored: apply always hands back the receiver.

also: do something on the side

also passes the object as it and returns the object. Think of it as "and also do this with it": logging, debugging, validation, registering the object somewhere. Because it returns the object unchanged, you can insert it into a chain without changing the chain's meaning:

Kotlin also for side effects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get sorted: [1, 3, 5, 9], scaled: [10, 30, 50, 90], 180, [1, 2, 3, 4], created id 7 and 8. also is the right choice for a debug print in the middle of a pipeline, because removing it later changes nothing.

apply or also?

Both return the object. Pick apply when you configure the object (members accessed through this), and also when you use the object in a side effect (passed as it). The names read well too: "apply these settings", "also log this".

takeIf and takeUnless

Two related helpers are not scope functions in the strict sense, but they are used together with let. takeIf returns the object if a condition holds and null otherwise; takeUnless is the opposite:

Kotlin takeIf and takeUnless

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 42, null, anonymous and valid: [email protected]. The pattern value.takeIf { condition }?.let { ... } replaces an if statement that checks a condition and then uses the value.

Pitfalls

Nesting confuses this and it

When you nest scope functions that use this, the inner this hides the outer one. Readers (and sometimes the compiler) have a hard time knowing which object a call belongs to:

Kotlin Nested this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints inner name: Alan, outer name: Ada and outer again: Ada. Inside the inner block a bare name means Alan's name, and you can only reach Ada through a label you put on the outer lambda (outer@{). Most readers will stumble here. Better to avoid the situation: store the receiver in a val, or use also/let with named parameters (ada.let { a -> alan.let { b -> ... } }). Rule of thumb: do not nest scope functions more than one level deep.

Wrong function for the job

Using it where the function gives this (or the reverse) is a compile error:

Kotlin it inside apply (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers with main.kt:3:9: error: unresolved reference 'it'. In apply the object is this. Write append("hello"), or switch to also if you prefer it.

Another classic mistake is expecting the object back from let or run:

Kotlin Forgetting that let returns the lambda result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 3 and abcdef. If you want the object afterwards, use apply or also.

Choosing quickly

  • Null check or transformation of a value: ?.let { ... }.
  • Configure a new object: apply.
  • Side effect, logging, or debugging in a chain: also.
  • Compute a result from several members of an object: run or with.
  • Block that produces a value without any receiver: run { ... }.

Do not use scope functions just because you can. If a plain statement is easier to read, write the statement. Chains of three scope functions in one expression, each changing this, are harder to follow than the three lines they replace. Also, since all five are inline, they cost nothing at run time (see Inline Functions), so the decision is purely about readability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which scope function passes the object as it and returns the object itself?

    also uses it as the object reference and returns the object. let returns the lambda result; apply returns the object but uses this.
  2. 2. What does Server().apply { port = 8080 } return?

    apply always returns the receiver object, which makes it ideal for configuring a newly created object.
  3. 3. What is ?.let { ... } most often used for?

    The safe call skips the block when the receiver is null; inside the block, it is non-null.
  4. 4. Which line fails to compile?

    apply provides the object as this, not it, so it is an unresolved reference.
  5. 5. What does "".takeUnless { it.isEmpty() } evaluate to?

    takeUnless returns the object unless the condition holds; here the string is empty, so the condition is true and the result is null.

Summary

  • Each scope function differs in two ways: the object is this or it, and the result is the lambda value or the object.
  • let (it, result), run and with (this, result), apply (this, object), also (it, object).
  • Use ?.let for null handling, apply for configuration, also for side effects, run and with to compute a result.
  • takeIf and takeUnless return the value or null and pair well with ?.let.
  • Do not nest them deeply: this inside this becomes hard to read.

Next: Infix Functions and Operator Overloading