Skip to content

Sealed Results & Switch

The Course
•
20 min study

An operation can have several meaningful outcomes with different data. A sealed interface lists the allowed implementations. Records can carry the data for each outcome, and a pattern switch can handle those cases explicitly. This is useful when one nullable result cannot explain what happened.

Understand the contract

sealed interface Outcome permits Accepted, Rejected declares a closed family. Each direct implementation must be final, sealed or explicitly non-sealed; records are already final. The example records implement Outcome just as classes implemented interfaces in intermediate. Keep these types together in one source file for the first exercise.

A switch expression produces a value. case Accepted accepted -> ... checks the runtime type and gives that case a variable of the narrower type. The arrow's expression becomes the switch result; there is no fall-through into the next case. These are type-pattern cases, not string labels: Accepted names a type, and accepted is the local variable you choose for that matching value. The interface itself has no fields to inspect; each record supplies its own accessors. A semicolon ends the assignment or return containing the switch. With a sealed family, covering all permitted cases makes the switch exhaustive. If you add another outcome, the compiler asks you to handle it.

This replaces the combination “boolean success plus maybe-null value plus maybe-null error,” which could represent contradictory states. It does not remove validation: a Rejected record still needs a meaningful message if your contract promises one. In these first examples outcomes are nonnull; null is not silently treated as rejection.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        System.out.println(describe(new Accepted(3)));
        System.out.println(describe(new Rejected("blank title")));
    }

    static String describe(Outcome outcome) {
        return switch (outcome) {
            case Accepted accepted -> "Accepted: " + accepted.count();
            case Rejected rejected -> "Rejected: " + rejected.message();
        };
    }
}

sealed interface Outcome permits Accepted, Rejected {}
record Accepted(int count) implements Outcome {}
record Rejected(String message) implements Outcome {}
Check your prediction
Text
Accepted: 3
Rejected: blank title

Trace a different case

Pattern matching also works with instanceof. value instanceof Accepted accepted checks the type and introduces the variable only on the matching path. Null does not match. This is useful for one focused question, while a switch is clearer when every alternative needs an answer. Unlike an unchecked cast, the pattern ties access to a successful type check.

Compare the boundary case Java
public class Main {
    public static void main(String[] args) {
        Outcome value = new Accepted(0);
        if (value instanceof Accepted accepted) {
            System.out.println(accepted.count());
        }
        Outcome missing = null;
        System.out.println(missing instanceof Accepted);
    }
}

sealed interface Outcome permits Accepted, Rejected {}
record Accepted(int count) implements Outcome {}
record Rejected(String message) implements Outcome {}
Check your prediction
Text
0
false

Choose a result family by the data each branch needs

An enum can distinguish ACCEPTED from REJECTED, but it does not by itself attach a count to one and an error message to the other. Separate records let each alternative require its own data, while a sealed interface states which alternatives callers must consider.

Draw the result as one box of one variant. Do not draw an object with success=true, value=null and message="failed": that contradictory combination is exactly what this model avoids. Constructor validation still protects each component's meaning.

Optional is simpler for a present-or-absent query. A result family is useful when different missing or rejected outcomes need different responses. Choose the smallest representation that preserves the decisions your caller actually needs, rather than replacing every return type with a large hierarchy.

Build it yourself

Exercise

Sealed Results & Switch: practice

Define sealed Lookup with records Found(String title) and Missing(String id). Write display(Lookup) returning "Title: Read" for Found("Read") and "Missing: A1" for Missing("A1"). Inputs and record components are nonnull for this exercise. Use an exhaustive switch with no default branch.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Each alternative carries the data needed to explain that outcome, without unrelated nullable fields.

Hint 2: a first step

Use the pattern variable in each case to call that record's generated accessor.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(display(new Found("Read")));
        System.out.println(display(new Missing("A1")));
    }

    static String display(Lookup result) {
        return switch (result) {
            case Found found -> "Title: " + found.title();
            case Missing missing -> "Missing: " + missing.id();
        };
    }
}

sealed interface Lookup permits Found, Missing {}
record Found(String title) implements Lookup {}
record Missing(String id) implements Lookup {}

Expected output:

Text
Title: Read
Missing: A1

The switch has one case per permitted record and no default. That is the point: if you later add record Invalid(String message) implements Lookup, display fails to compile until it handles the new case. A default branch would silently format the new case as something else. Each case binds a typed variable, so found.title() needs no cast.

Change it and test again

Add a third record Forbidden(String reason), add it to permits, and compile before changing display. Read the missing-case diagnostic, then add a case with a deliberate message. Restore the two-case exercise afterward. Avoid a default branch that hides the need to review a newly added outcome.

Explain before moving on

Compare this model with Optional: Optional answers whether a value exists, while a result family can explain different outcomes. What invalid combinations did the separate records prevent? What invalid component values still need constructor validation?

Was this article helpful?

Your response is saved on this device.