Skip to workspace
Kotlin Lab

Designing Kotlin APIs / Chapter 02

Render every response state

Make adding a network outcome a compiler-visible UI change.

The decision

A search endpoint returns a page, a retry delay, or an offline signal. A page and a delay each carry a non-negative integer with a different meaning. The UI must render all three states.

Read the Kotlin

Match the variant before reading its payload

The outer when (response) picks a variant. Inside an is branch the compiler narrows the receiver so its payload becomes available. Trace zero separately inside each variant. A successful page with zero results and a retry with zero seconds have different meanings even though both carry the same integer.

Response.Page(0)   // an empty result page
Response.Retry(0)  // a retry that can start immediately

Let the compiler identify renderers that need a decision

A when expression must yield a value for every possible case. Cover all variants of a sealed family explicitly and a new uncovered variant breaks compilation at the renderer. Adding a catch-all else will keep that renderer compiling as the family grows. Review the label that catch-all would give to a newly added state.

Decide whether each occurrence carries its own data

A data object gives a payload-free state one named instance. A data class lets each response carry different values through its constructor. If two offline messages can report different last-sync times, storing the time on a shared singleton would mix their state. Give each response its own timestamp instead.

data object Loading
data class Paused(val secondsRemaining: Int)

The full example

Java 25
class Lesson {
    sealed interface Response permits Page, Retry, Offline {}
    record Page(int count) implements Response {}
    record Retry(int seconds) implements Response {}
    record Offline() implements Response {}

    static String screenText(Response response) {
        return switch (response) {
            case Page(var n) -> n == 0 ? "No results" : "Results: " + n;
            case Retry(var s) -> s == 0 ? "Retry now" : "Retry in " + s + "s";
            case Offline ignored -> "Offline";
        };
    }
}
Kotlin/JVM
sealed interface Response {
    data class Page(val count: Int) : Response
    data class Retry(val seconds: Int) : Response
    data object Offline : Response
}

fun screenText(response: Response): String = when (response) {
    is Response.Page -> if (response.count == 0) "No results" else "Results: ${response.count}"
    is Response.Retry -> if (response.seconds == 0) "Retry now" else "Retry in ${response.seconds}s"
    Response.Offline -> "Offline"
}

Inputs and outcomes

InputOutcomeWhy it matters
Page with zero resultsNo resultsAn empty page is a successful response.
Retry after zero secondsRetry nowZero describes an immediate retry.
OfflineOfflineThere is no result count or delay in this state.

Walk through the code

  1. The sealed interface fixes the family of direct variants. The compiler checks the Kotlin when expression and the Java 25 pattern switch for exhaustiveness.
  2. An is branch narrows response to the matching subtype, making just that payload available. The singleton Offline needs no payload or constructor call.
  3. The two zero cases live inside different branches. Flattening them into a single status and number makes it easier to conflate a successful empty result with a failed call.

The Java habit

Adding else -> "Offline" to silence an exhaustiveness error turns every future response into an offline screen. Without the fallback, recompilation points to each decision that needs a new branch.

When to choose differently

If independent plugins must define their own outcomes outside the module, a closed hierarchy works against that extension model. An interface with a rendering operation or registered handlers may fit better.

References

Open quizTry code