Skip to workspace
Kotlin Lab

Designing Kotlin APIs / Chapter 01

Choose a scope function

Choose which job a caller receives when saving a configured draft produces a normalized copy.

The decision

A library gives you a mutable ExportJob with defaults. For a nonempty owner, set the owner and enable audit. Otherwise retain the batch owner with auditing off. Clamp the number of attempts to 1 through 5.

Read the Kotlin

Follow the object that leaves the block

In apply the object becomes this, so assignments such as owner = ... affect it directly. In also the same object is an argument, usually called it. Both functions return the original receiver. A callback may create a different object, but the chain continues with the original even if the callback returns its copy.

val draft = ExportJob().apply { owner = "Jo" }
val sent = draft.also { saveCopy(it) }
sent === draft  // true

Switch receivers only when the next step needs the result

Read let as a transformation. Its result is the last expression inside the block. When saving creates a new job, use that result as the receiver for anything that must observe the saved version. When the caller needs to keep editing the draft, perform side effects inside also and allow the draft to continue down the chain.

val receipt = draft.let { save(it) }.also { audit(it) }
val editable = draft.also { printLabel(normalize(it)) }

Count calls as well as following values

A scope function executes its block when the chain reaches it. No result is memoized between two blocks. Mark each call to the revision-producing function on paper, then mark the receiver that leaves each block. Two observers can end up with different revisions even though one expression started the chain.

val first = draft.let { save(it) }
first.also { save(draft) }  // saves again, expression still returns first

The full example

Java 25
class Lesson {
    static class ExportJob {
        String owner = "batch";
        int attempts = 1;
        boolean audited;
    }

    static ExportJob exportJob(String requestedOwner, int budget) {
        var job = new ExportJob();
        if (!requestedOwner.isEmpty()) {
            job.owner = requestedOwner;
            job.audited = true;
        }
        job.attempts = Math.clamp(budget, 1, 5);
        return job;
    }
}
Kotlin/JVM
class ExportJob {
    var owner = "batch"
    var attempts = 1
    var audited = false
}

fun exportJob(requestedOwner: String, budget: Int): ExportJob =
    ExportJob().apply {
        if (requestedOwner.isNotEmpty()) {
            owner = requestedOwner
            audited = true
        }
        attempts = budget.coerceIn(1, 5)
    }

Inputs and outcomes

InputOutcomeWhy it matters
Owner Ada, budget 3Ada / 3 / trueThe caller can submit the configured object.
Empty owner, budget 0batch / 1 / falsePreserve its existing owner and audit defaults.
Owner Lin, budget 12Lin / 5 / trueThe cap applies independently of ownership.

Walk through the code

  1. Java names the new object before updating it. Kotlin apply makes that object the receiver of the block, so owner and attempts address its properties.
  2. apply returns the configured object even though the final line assigns a field. also returns the object too and supplies it as a lambda argument. A named argument can make nested contexts easier to follow.
  3. let and run return the block’s result. They suit a conversion, such as turning a configured job into its display label.

The Java habit

An unqualified owner = owner can silently assign a property to itself or confuse a parameter and a property. Use distinct names or qualify the receiver with this.

When to choose differently

An immutable request with a small number of known fields usually reads better as a constructor with named arguments. apply earns its place when the underlying API really is mutable.

References

Open quizTry code