Skip to content
tezvyn:

Kotlin Scope Functions: Cleaner Code, Clearer Choices

Source: kotlinlang.orgHardHow cards are made

Kotlin Scope Functions: Cleaner Code, Clearer Choices

Kotlin's scope functions (let, run, apply) create a temporary workspace for an object, avoiding repetitive variable names. Use them for object configuration or chaining calls.

Why it exists

To reduce boilerplate code. Without scope functions, performing multiple operations on an object requires creating a temporary variable and repeating its name for every call. This is verbose and clutters the local scope. Scope functions offer a more concise and expressive way to execute a block of code in the context of an object.

The mental model

Think of a scope function as putting an object on a temporary workbench. Instead of repeatedly saying "take the person object and set its age," then "take the person object and set its city," you say, "here's the person object; on it, set the age and city." The function's lambda is the workbench, giving you direct access to the object for a series of tasks.

How it works

All five scope functions (let, run, with, apply, also) execute a code block on a context object, but they differ in two ways. First is the object reference: let and also refer to the object as it (a lambda argument), while run, with, and apply refer to it as this (a lambda receiver). Second is the return value: apply and also return the context object itself, while let, run, and with return the result of the lambda expression.

When to use it

Choose based on your intent. For object configuration where you need to return the configured object, use apply. To execute a block on a non-nullable object and perhaps return a new result type, use let. To perform a series of operations on an object and compute a final result, run is a good fit. For adding side-effects like logging without modifying the call chain, use also.

When not to use it

Avoid scope functions for single, simple operations; a direct method call is clearer. The biggest anti-pattern is nesting multiple scope functions. It becomes extremely difficult to reason about which this or it is in scope at any given moment, leading to subtle bugs and unreadable code. If your lambda becomes complex, refactor it into a proper function with a named variable.

One canonical example

Configuring a new object is the classic use case for apply. Without it, you'd write: val person = Person("Alice"); person.age = 30; person.city = "London";. With apply, this becomes a single, fluent expression: val person = Person("Alice").apply { age = 30; city = "London" }. The apply block uses this implicitly to refer to the Person instance and returns the instance itself, making it perfect for initialization chains.

Interview question

Which scenario is explicitly identified as the biggest anti-pattern when utilizing Kotlin's scope functions?

  • a.Nesting multiple scope functions within each other.Correct
  • b.Returning a different data type from the lambda than the context object.
  • c.Using a scope function for a single, straightforward operation.
  • d.Referring to the context object using 'it' when 'this' could be used.
Why?

B is correct because the card explicitly states, "The biggest anti-pattern is nesting multiple scope functions. It becomes extremely difficult to reason about which this or it is in scope at any given moment, leading to subtle bugs and unreadable code." Option C, while something to avoid for clarity, is not labeled as the "biggest anti-pattern"; nesting is highlighted due to its complexity and potential for subtle bugs.

Just read this? Test yourself on what you have been reading.

Read the original → kotlinlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on kotlin — each one lists the topics its interview covers.

See open roles