CodeBlanks Logo Icon CodeBlanks

Scope functions

Learn let, run, apply, also and with scope functions.

Scope functions

Scope functions work on an object in a temporary scope. Kotlin has five: let, run, apply, also and with.

Example: val list = mutableListOf<Int>().apply { add(1); add(2) }. apply configures the object and returns it. Calling val s = "hi".let { it.uppercase() } returns "HI". let produces a return value; apply returns the object. Each scope function gives a different context; the right choice makes code short and readable.

apply and let

apply and let are the most common scope functions. apply suits configuration, let suits transformation.

Example: val list = mutableListOf<Int>().apply { add(1); add(2) } returns [1, 2]. val upper = "hi".let { it.uppercase() } returns "HI". Inside apply, this refers to the object; inside let, it refers to the object. Which scope function to choose depends on the goal.

Practice Using apply and let

Declare val list = mutableListOf<Int>().apply { add(1); add(2) }. Declare val upper = "hi".let { it.uppercase() }. In main call println(list) and println(upper) on separate lines.

Starter code

Main.kt
// list: add 1 and 2 with apply
// upper: uppercase with let
// print both in main

Sample solution

Main.kt
val list = mutableListOf<Int>().apply { add(1); add(2) }
val upper = "hi".let { it.uppercase() }

fun main() {
    println(list)
    println(upper)
}

Expected output

[1, 2]
HI

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the scope functions

Term Meaning
let Produces a return value
run Runs code on the object
apply Returns the object, this
also Returns the object, it

2 Which scope function configures an object and returns it?

  • apply Correct answer
  • run
  • let
  • with

Explanation: apply configures the object and returns it.

3 Complete the object with apply

Question
val list = mutableListOf<Int>().____ { add(1); add(2) }
Answer
val list = mutableListOf<Int>().apply { add(1); add(2) }

Explanation: apply configures the object and returns it.

All lessons in Intermediate