Interview QuestionPractical QuestionFollow-up Questions

Kotlin Scope Functions

skydovesJaewoong Eum (skydoves)||7 min read

Kotlin Scope Functions

Scope functions are a set of functions in the Kotlin standard library that execute a block of code within the context of an object. They reduce boilerplate, improve readability, and provide a structured way to configure objects, perform null checks, and chain operations. The five scope functions are let, run, with, apply, and also. By the end of this lesson, you will be able to:

  • Describe the context object and return value of each scope function.
  • Choose the appropriate scope function for a given use case.
  • Explain the difference between this and it as context references.
  • Avoid common mistakes when nesting scope functions.

Context Reference: this vs. it

Scope functions differ in how they expose the context object inside the lambda:

  • this (receiver): Used by run, with, and apply. The object becomes the receiver, so you can call its methods directly without a qualifier.
  • it (argument): Used by let and also. The object is passed as a lambda parameter, requiring you to reference it explicitly.

This distinction affects readability. Use this when the block primarily calls methods on the object. Use it when the block passes the object to other functions or when a named reference improves clarity.

let

let passes the object as it and returns the result of the lambda. It is commonly used for null safe operations and transforming a value:

val name: String? = "skydoves"
val greeting = name?.let { "Hello, $it!" }
println(greeting) // Output: Hello, skydoves!

The block executes only when name is not null. The result of the last expression becomes the return value of let.

let is also useful for introducing a named reference to an expression result within a limited scope, avoiding the need for a temporary variable:

findUserById(42)?.let { user ->
    sendWelcomeEmail(user)
    logUserActivity(user)
}

run

run provides the object as this and returns the result of the lambda. It is useful when you need to both operate on an object and compute a result:

This interview continues for subscribers

Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.

Become a Sponsor