let, run, with, apply, also

Kotlin language Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

fun main() {
    val a = "kotlin".let { it.length }
    val b = "kotlin".also { it.length }
    val c = StringBuilder().apply { append("hi") }.toString()
    println("$a $b $c")
}
Options
Hint 1 of 1

Which of these return the receiver?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 6 kotlin hi

Correct. let returns the lambda result, also returns the receiver, apply returns the builder.

Why not the others?
  • B 6 6 hi. also returns the original object, not the lambda's value.
  • C kotlin kotlin hi. let returns the lambda's result, the length.
  • D 6 kotlin StringBuilder. toString() turns the builder into "hi".

30-second answer

They differ in two ways: how the object is referenced inside (it for let/also, this for run/with/apply) and what they return (the lambda result for let/run/with, the object itself for apply/also). Use apply to configure an object, also for side effects like logging, let for null checks and transforms, and run or with to compute a result from an object.

Practise saying it · 30 s. No recording, just a timer

Explain how to pick a scope function.

Say your answer out loud, then check which of these points you covered:

  • it vs this
  • Lambda result vs receiver
  • apply to configure, also for side effects
  • let for null checks

Deep dive

x?.let { } runs only when x isn't null.

apply is ideal for builders: Intent(...).apply { putExtra(...) }.

also keeps a chain readable when you add logging or validation.

Nesting scope functions hurts readability; name things instead.

letitlambda resultnull checks, transforms
runthislambda resultcompute from an object
withthislambda resultgroup calls on an object
applythisthe objectconfigure a builder
alsoitthe objectlogging, side effects

Common mistakes

  • Nesting let inside let inside apply.
  • Using apply when you need the lambda's result.
  • Replacing a simple if with ?.let { } ?: run { }.

Senior take & follow-ups

A two-by-two table (this/it × result/receiver) answers this faster than listing all five.

Follow-up questions

Think of your answer first, then open the hint.

  1. Which return the receiver?

    Show hint

    apply and also.

  2. Which use it?

    Show hint

    let and also.

Suggest a fix if something here is wrong or out of date.