Scope Functions Flashcards
KOTLIN › Language Idioms
- What does apply return and how does it reference the object?
- apply returns the context object itself (the receiver) and references it as this. Ideal for configuring an object and returning it.
- What does also return and how does it reference the object?
- also returns the context object itself and references it as it. Used for side effects like logging or validation within a chain.
- What does let return and how does it reference the object?
- let returns the lambda result and references the object as it. Common for null-checks via ?.let and transforming a value.
- How do run and with differ from let in their return value and reference?
- run and with both return the lambda result but reference the object as this (receiver), whereas let returns the lambda result but uses it.
- Which scope functions return the context object rather than the lambda result?
- Only apply and also return the context object. let, run, and with return the lambda result.
- Why is ?.let preferred for null-checks?
- The safe call ?.let runs the lambda only when the receiver is non-null, and inside it the value is smart-cast to non-null, avoiding a separate null guard.
- What is the difference between run as an extension and the non-extension run?
- Extension run is called on an object (obj.run { }) with this as receiver. Non-extension run takes no object and just executes a block of statements where an expression is needed.
- When would you choose apply over also for object configuration?
- Use apply when assigning the object's own properties (this lets you write them bare). Use also when you need the object as an argument, e.g. passing it to a logger as it.
- What is the key difference between with and run?
- Both use this and return the lambda result, but with is a non-extension taking the object as an argument (with(obj){ }), while run is an extension called on a nullable-safe receiver (obj.run{ }).