Scope Functions

The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions. There are five of them: let, run, with, apply, and also.

Basically, these functions do the same: execute a block of code on an object. What’s different is how this object becomes available inside the block and what is the result of the whole expression.

Here’s a typical usage of a scope function:

  1. data class Person(var name: String, var age: Int, var city: String) {
  2. fun moveTo(newCity: String) { city = newCity }
  3. fun incrementAge() { age++ }
  4. }
  5. fun main() {
  6. //sampleStart
  7. Person("Alice", 20, "Amsterdam").let {
  8. println(it)
  9. it.moveTo("London")
  10. it.incrementAge()
  11. println(it)
  12. }
  13. //sampleEnd
  14. }

If you write the same without let, you’ll have to introduce a new variable and repeat its name whenever you use it.

  1. data class Person(var name: String, var age: Int, var city: String) {
  2. fun moveTo(newCity: String) { city = newCity }
  3. fun incrementAge() { age++ }
  4. }
  5. fun main() {
  6. //sampleStart
  7. val alice = Person("Alice", 20, "Amsterdam")
  8. println(alice)
  9. alice.moveTo("London")
  10. alice.incrementAge()
  11. println(alice)
  12. //sampleEnd
  13. }

The scope functions do not introduce any new technical capabilities, but they can make your code more concise and readable.

Due to the similar nature of scope functions, choosing the right one for your case can be a bit tricky. The choice mainly depends on your intent and the consistency of use in your project. Below we’ll provide detailed descriptions of the distinctions between scope functions and the conventions on their usage.

Distinctions

Because the scope functions are all quite similar in nature, it’s important to understand the differences between them. There are two main differences between each scope function:

  • The way to refer to the context object
  • The return value.

Context object: this or it

Inside the lambda of a scope function, the context object is available by a short reference instead of its actual name. Each scope function uses one of two ways to access the context object: as a lambda receiver (this) or as a lambda argument (it). Both provide the same capabilities, so we’ll describe the pros and cons of each for different cases and provide recommendations on their use.

  1. fun main() {
  2. val str = "Hello"
  3. // this
  4. str.run {
  5. println("The receiver string length: $length")
  6. //println("The receiver string length: ${this.length}") // does the same
  7. }
  8. // it
  9. str.let {
  10. println("The receiver string's length is ${it.length}")
  11. }
  12. }

this

run, with, and apply refer to the context object as a lambda receiver - by keyword this. Hence, in their lambdas, the object is available as it would be in ordinary class functions. In most cases, you can omit this when accessing the members of the receiver object, making the code shorter. On the other hand, if this is omitted, it can be hard to distinguish between the receiver members and external objects or functions. So, having the context object as a receiver (this) is recommended for lambdas that mainly operate on the object members: call its functions or assign properties.

  1. data class Person(var name: String, var age: Int = 0, var city: String = "")
  2. fun main() {
  3. //sampleStart
  4. val adam = Person("Adam").apply {
  5. age = 20 // same as this.age = 20 or adam.age = 20
  6. city = "London"
  7. }
  8. println(adam)
  9. //sampleEnd
  10. }

it

In turn, let and also have the context object as a lambda argument. If the argument name is not specified, the object is accessed by the implicit default name it. it is shorter than this and expressions with it are usually easier for reading. However, when calling the object functions or properties you don’t have the object available implicitly like this. Hence, having the context object as it is better when the object is mostly used as an argument in function calls. it is also better if you use multiple variables in the code block.

  1. import kotlin.random.Random
  2. fun writeToLog(message: String) {
  3. println("INFO: $message")
  4. }
  5. fun main() {
  6. //sampleStart
  7. fun getRandomInt(): Int {
  8. return Random.nextInt(100).also {
  9. writeToLog("getRandomInt() generated value $it")
  10. }
  11. }
  12. val i = getRandomInt()
  13. //sampleEnd
  14. }

Additionally, when you pass the context object as an argument, you can provide a custom name for the context object inside the scope.

  1. import kotlin.random.Random
  2. fun writeToLog(message: String) {
  3. println("INFO: $message")
  4. }
  5. fun main() {
  6. //sampleStart
  7. fun getRandomInt(): Int {
  8. return Random.nextInt(100).also { value ->
  9. writeToLog("getRandomInt() generated value $value")
  10. }
  11. }
  12. val i = getRandomInt()
  13. //sampleEnd
  14. }

Return value

The scope functions differ by the result they return:

  • apply and also return the context object.
  • let, run, and with return the lambda result.

These two options let you choose the proper function depending on what you do next in your code.

Context object

The return value of apply and also is the context object itself. Hence, they can be included into call chains as side steps: you can continue chaining function calls on the same object after them.

  1. fun main() {
  2. //sampleStart
  3. val numberList = mutableListOf<Double>()
  4. numberList.also { println("Populating the list") }
  5. .apply {
  6. add(2.71)
  7. add(3.14)
  8. add(1.0)
  9. }
  10. .also { println("Sorting the list") }
  11. .sort()
  12. //sampleEnd
  13. println(numberList)
  14. }

They also can be used in return statements of functions returning the context object.

  1. import kotlin.random.Random
  2. fun writeToLog(message: String) {
  3. println("INFO: $message")
  4. }
  5. fun main() {
  6. //sampleStart
  7. fun getRandomInt(): Int {
  8. return Random.nextInt(100).also {
  9. writeToLog("getRandomInt() generated value $it")
  10. }
  11. }
  12. val i = getRandomInt()
  13. //sampleEnd
  14. }

Lambda result

let, run, and with return the lambda result. So, you can use them when assigning the result to a variable, chaining operations on the result, and so on.

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three")
  4. val countEndsWithE = numbers.run {
  5. add("four")
  6. add("five")
  7. count { it.endsWith("e") }
  8. }
  9. println("There are $countEndsWithE elements that end with e.")
  10. //sampleEnd
  11. }

Additionally, you can ignore the return value and use a scope function to create a temporary scope for variables.

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three")
  4. with(numbers) {
  5. val firstItem = first()
  6. val lastItem = last()
  7. println("First item: $firstItem, last item: $lastItem")
  8. }
  9. //sampleEnd
  10. }

Functions

To help you choose the right scope function for your case, we’ll describe them in detail and provide usage recommendations. Technically, functions are interchangeable in many cases, so the examples show the conventions that define the common usage style.

let

The context object is available as an argument (it). The return value is the lambda result.

let can be used to invoke one or more functions on results of call chains. For example, the following code prints the results of two operations on a collection:

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three", "four", "five")
  4. val resultList = numbers.map { it.length }.filter { it > 3 }
  5. println(resultList)
  6. //sampleEnd
  7. }

With let, you can rewrite it:

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three", "four", "five")
  4. numbers.map { it.length }.filter { it > 3 }.let {
  5. println(it)
  6. // and more function calls if needed
  7. }
  8. //sampleEnd
  9. }

If the code block contains a single function with it as an argument, you can use the method reference (::) instead of the lambda:

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three", "four", "five")
  4. numbers.map { it.length }.filter { it > 3 }.let(::println)
  5. //sampleEnd
  6. }

let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the safe call operator ?. on it and call let with the actions in its lambda.

  1. fun processNonNullString(str: String) {}
  2. fun main() {
  3. //sampleStart
  4. val str: String? = "Hello"
  5. //processNonNullString(str) // compilation error: str can be null
  6. val length = str?.let {
  7. println("let() called on $it")
  8. processNonNullString(it) // OK: 'it' is not null inside '?.let { }'
  9. it.length
  10. }
  11. //sampleEnd
  12. }

Another case for using let is introducing local variables with a limited scope for improving code readability. To define a new variable for the context object, provide its name as the lambda argument so that it can be used instead of the default it.

  1. fun main() {
  2. //sampleStart
  3. val numbers = listOf("one", "two", "three", "four")
  4. val modifiedFirstItem = numbers.first().let { firstItem ->
  5. println("The first item of the list is '$firstItem'")
  6. if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
  7. }.toUpperCase()
  8. println("First item after modifications: '$modifiedFirstItem'")
  9. //sampleEnd
  10. }

with

A non-extension function: the context object is passed as an argument, but inside the lambda, it’s available as a receiver (this). The return value is the lambda result.

We recommend with for calling functions on the context object without providing the lambda result. In the code, with can be read as “with this object, do the following.

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three")
  4. with(numbers) {
  5. println("'with' is called with argument $this")
  6. println("It contains $size elements")
  7. }
  8. //sampleEnd
  9. }

Another use case for with is introducing a helper object whose properties or functions will be used for calculating a value.

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three")
  4. val firstAndLast = with(numbers) {
  5. "The first element is ${first()}," +
  6. " the last element is ${last()}"
  7. }
  8. println(firstAndLast)
  9. //sampleEnd
  10. }

run

The context object is available as a receiver (this). The return value is the lambda result.

run does the same as with but invokes as let - as an extension function of the context object.

run is useful when your lambda contains both the object initialization and the computation of the return value.

  1. class MultiportService(var url: String, var port: Int) {
  2. fun prepareRequest(): String = "Default request"
  3. fun query(request: String): String = "Result for query '$request'"
  4. }
  5. fun main() {
  6. //sampleStart
  7. val service = MultiportService("https://example.kotlinlang.org", 80)
  8. val result = service.run {
  9. port = 8080
  10. query(prepareRequest() + " to port $port")
  11. }
  12. // the same code written with let() function:
  13. val letResult = service.let {
  14. it.port = 8080
  15. it.query(it.prepareRequest() + " to port ${it.port}")
  16. }
  17. //sampleEnd
  18. println(result)
  19. println(letResult)
  20. }

Besides calling run on a receiver object, you can use it as a non-extension function. Non-extension run lets you execute a block of several statements where an expression is required.

  1. fun main() {
  2. //sampleStart
  3. val hexNumberRegex = run {
  4. val digits = "0-9"
  5. val hexDigits = "A-Fa-f"
  6. val sign = "+-"
  7. Regex("[$sign]?[$digits$hexDigits]+")
  8. }
  9. for (match in hexNumberRegex.findAll("+1234 -FFFF not-a-number")) {
  10. println(match.value)
  11. }
  12. //sampleEnd
  13. }

apply

The context object is available as a receiver (this). The return value is the object itself.

Use apply for code blocks that don’t return a value and mainly operate on the members of the receiver object. The common case for apply is the object configuration. Such calls can be read as “apply the following assignments to the object.

  1. data class Person(var name: String, var age: Int = 0, var city: String = "")
  2. fun main() {
  3. //sampleStart
  4. val adam = Person("Adam").apply {
  5. age = 32
  6. city = "London"
  7. }
  8. println(adam)
  9. //sampleEnd
  10. }

Having the receiver as the return value, you can easily include apply into call chains for more complex processing.

also

The context object is available as an argument (it). The return value is the object itself.

also is good for performing some actions that take the context object as an argument. Use also for actions that need a reference rather to the object than to its properties and functions, or when you don’t want to shadow this reference from an outer scope.

When you see also in the code, you can read it as “and also do the following with the object.

  1. fun main() {
  2. //sampleStart
  3. val numbers = mutableListOf("one", "two", "three")
  4. numbers
  5. .also { println("The list elements before adding new one: $it") }
  6. .add("four")
  7. //sampleEnd
  8. }

Function selection

To help you choose the right scope function for your purpose, we provide the table of key differences between them.

FunctionObject referenceReturn valueIs extension function
letitLambda resultYes
runthisLambda resultYes
run-Lambda resultNo: called without the context object
withthisLambda resultNo: takes the context object as an argument.
applythisContext objectYes
alsoitContext objectYes

Here is a short guide for choosing scope functions depending on the intended purpose:

  • Executing a lambda on non-null objects: let
  • Introducing an expression as a variable in local scope: let
  • Object configuration: apply
  • Object configuration and computing the result: run
  • Running statements where an expression is required: non-extension run
  • Additional effects: also
  • Grouping function calls on an object: with

The use cases of different functions overlap, so that you can choose the functions based on the specific conventions used in your project or team.

Although the scope functions are a way of making the code more concise, avoid overusing them: it can decrease your code readability and lead to errors. Avoid nesting scope functions and be careful when chaining them: it’s easy to get confused about the current context object and the value of this or it.

takeIf and takeUnless

In addition to scope functions, the standard library contains the functions takeIf and takeUnless. These functions let you embed checks of the object state in call chains.

When called on an object with a predicate provided, takeIf returns this object if it matches the predicate. Otherwise, it returns null. So, takeIf is a filtering function for a single object. In turn, takeUnless returns the object if it doesn’t match the predicate and null if it does. The object is available as a lambda argument (it).

  1. import kotlin.random.*
  2. fun main() {
  3. //sampleStart
  4. val number = Random.nextInt(100)
  5. val evenOrNull = number.takeIf { it % 2 == 0 }
  6. val oddOrNull = number.takeUnless { it % 2 == 0 }
  7. println("even: $evenOrNull, odd: $oddOrNull")
  8. //sampleEnd
  9. }

When chaining other functions after takeIf and takeUnless, don’t forget to perform the null check or the safe call (?.) because their return value is nullable.

  1. fun main() {
  2. //sampleStart
  3. val str = "Hello"
  4. val caps = str.takeIf { it.isNotEmpty() }?.toUpperCase()
  5. //val caps = str.takeIf { it.isNotEmpty() }.toUpperCase() //compilation error
  6. println(caps)
  7. //sampleEnd
  8. }

takeIf and takeUnless are especially useful together with scope functions. A good case is chaining them with let for running a code block on objects that match the given predicate. To do this, call takeIf on the object and then call let with a safe call (?). For objects that don’t match the predicate, takeIf returns null and let isn’t invoked.

  1. fun main() {
  2. //sampleStart
  3. fun displaySubstringPosition(input: String, sub: String) {
  4. input.indexOf(sub).takeIf { it >= 0 }?.let {
  5. println("The substring $sub is found in $input.")
  6. println("Its start position is $it.")
  7. }
  8. }
  9. displaySubstringPosition("010000011", "11")
  10. displaySubstringPosition("010000011", "12")
  11. //sampleEnd
  12. }

This is how the same function looks without the standard library functions:

  1. fun main() {
  2. //sampleStart
  3. fun displaySubstringPosition(input: String, sub: String) {
  4. val index = input.indexOf(sub)
  5. if (index >= 0) {
  6. println("The substring $sub is found in $input.")
  7. println("Its start position is $index.")
  8. }
  9. }
  10. displaySubstringPosition("010000011", "11")
  11. displaySubstringPosition("010000011", "12")
  12. //sampleEnd
  13. }