๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Let and Run

let and run are scope functions that run a block on a value. Each one returns the value of the last expression in its block.

let after a safe call

The word is not null, so the let block runs. The block prints the length of the word.

fun main() {
    val word: String? = "Mira"
    word?.let {
        println(it.length)
    }
}

let as a transformation

let receives the name and returns an uppercase form. The new value is stored in a separate val.

fun main() {
    val name = "ana"
    val loud = name.let {
        it.uppercase()
    }
    println(loud)
}

run on a receiver

run makes the box the receiver of the block. Members of the box are read directly inside the block.

class Box(val label: String, val amount: Int)

fun main() {
    val box = Box("pens", 12)
    val text = box.run {
        "$label: $amount"
    }
    println(text)
}

A plain run block

The run block holds two local values and returns their product. The result is one number.

fun main() {
    val result = run {
        val first = 4
        val second = 5
        first * second
    }
    println(result)
}

Example

fun main() {
    val user: String? = "Sanjay"
    user?.let {
        println("Hello, $it")
    }
    val score = run {
        val first = 7
        val second = 8
        first + second
    }
    println(score)
    val upper = "kotlin".let {
        it.uppercase()
    }
    println(upper)
}

Key points

  • let makes the value available as it inside the block.
  • A safe call before let runs the block only when the value is not null.
  • let can turn one value into a different value.
  • run on a value makes that value the receiver inside the block.
  • A plain run block groups a few statements and returns a single value.

In this example, the safe call lets the block greet a non-null user. The plain run block adds two local values and returns 15. The last let turns the word into its uppercase form.

Note

The block result is the return value of let and run. The original value stays unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

When does the block in name?.let { } run?