Scope Functions Interview Questions

KOTLIN › Language Idioms

Explain let, apply, run, also and with. What does each one return, and how do you refer to the object inside?

What a strong answer covers: let and also pass the object as 'it'; run, apply and with make it 'this'. apply and also return the object itself, while let, run and with return the lambda's result. A strong answer gives a typical use for each: let for null checks and mapping, apply for configuring an object, also for side effects like logging, run and with for computing a value from an object.

Which scope function would you use to configure a newly created object, and which for running code only when a value is non-null? Why?

What a strong answer covers: apply for configuration, because 'this' makes property assignment read naturally and it returns the configured object, so it chains straight into an assignment. ?.let for the null case, because the safe call skips the block entirely when the value is null and gives you a smart-cast non-null 'it' inside.

What is the practical difference between also and apply? Give an example where picking the wrong one hurts readability.

What a strong answer covers: Both return the receiver, but also exposes it as 'it' and is meant for side effects that don't change the object (logging, validation, adding to a list), while apply exposes 'this' and is meant for setting it up. Using apply for logging makes 'this' ambiguous with the enclosing class; using also to set many properties means repeating 'it.' on every line.

Have you seen scope function chains hurt readability or debugging? Where do you draw the line in code review?

What a strong answer covers: Long chains like x.let{}.also{}.run{} compress several steps into one expression, nest implicit 'it' and 'this' receivers until it's unclear which object you mean, and give stack traces and breakpoints a single line. A strong answer keeps chains to one or two calls, names intermediate values when logic branches, never nests two 'it' lambdas, and treats scope functions as a readability tool rather than a style requirement.

Scope functions are inline. What does that mean for return statements, performance and bytecode, and when could deep nesting of them actually cost you?

What a strong answer covers: Because they're inline, the lambda body is pasted at the call site: no Function object is allocated, and a bare return inside returns from the enclosing function (non-local return), while return@let only exits the lambda. The cost is code duplication: heavily nested inline lambdas grow method bytecode, which can matter in hot or very large methods. A strong answer knows non-local returns can surprise readers and uses labelled returns deliberately.

Back to Scope Functions