Model results with sealed types
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Some failures are part of normal business: a wrong OTP, a low balance, an out-of-stock item. A Result type returns them as ordinary values, Success or Failure, so the method's return type itself says "this can fail", and the caller cannot use the value without first deciding what to do when it is missing.
Expected failures as values instead of error codes or exceptions
Older code reports a failure with an error code or with an exception. An error code is a special return value such as -1 or null, and nothing forces the caller to check it.
Example 1 · The old ways: an error code and an exception in a batch
import java.util.List;
public class OldWaysDemo { // returns -1 when the balance is too low static int withdrawCode(int balance, int amount) { return amount > balance ? -1 : balance - amount; }
static int withdrawOrThrow(int balance, int amount) { if (amount > balance) { throw new IllegalArgumentException("insufficient balance for Rs. " + amount); } return balance - amount; }
public static void main(String[] args) { int left = withdrawCode(500, 800); System.out.println("Balance shown to user: Rs. " + left);
List<Integer> requests = List.of(200, 900, 100); try { requests.stream() .map(r -> withdrawOrThrow(500, r)) .forEach(b -> System.out.println("Done, balance Rs. " + b)); } catch (IllegalArgumentException e) { System.out.println("Batch stopped: " + e.getMessage()); } }}Balance shown to user: Rs. -1 Done, balance Rs. 300 Batch stopped: insufficient balance for Rs. 900
What this code does
- The caller of
withdrawCodeforgot to check for-1, so the app shows a balance of minus one rupee. Nothing in the typeintwarned them. - The exception cannot be ignored, but it stops the stream: the third request, which would have worked, never runs. A low balance is an expected outcome and should not end the whole batch.
With an error code, balance - (-1) quietly adds a rupee. An exception cannot be ignored, but an unchecked one does not appear in the method's signature, it jumps out of the normal flow, and inside a stream one thrown exception stops the whole batch.
An expected failure is a result the business plans for: insufficient balance, an invalid PIN code, a seat already booked. It is not a bug, so it deserves a normal return value that carries the reason. A sealed type is perfect for this: the method returns Result<Integer>, which is either Success(value) or Failure(reason), and nothing else.
- Error code: easy to forget, carries no reason.
- Exception: cannot be forgotten, but hidden in the signature and stops a stream.
- Result value: visible in the type, carries the reason, flows through streams.
A Result type with Success and Failure records
Records can be generic, which means they take a type parameter like a List<T> does. So the whole Result type is three short declarations: sealed interface Result<T> permits Success, Failure, record Success<T>(T value) implements Result<T> and record Failure<T>(String error) implements Result<T>.
Example 2 · A Result type with Success and Failure records
sealed interface Result<T> permits Success, Failure { default boolean isSuccess() { return this instanceof Success; }
default T orElse(T fallback) { return this instanceof Success<T> s ? s.value() : fallback; }}
record Success<T>(T value) implements Result<T> { }
record Failure<T>(String error) implements Result<T> { }
public class ResultTypeDemo { static Result<Integer> withdraw(int balance, int amount) { if (amount <= 0) { return new Failure<>("amount must be positive"); } if (amount > balance) { return new Failure<>("insufficient balance: Rs. " + balance + " available"); } return new Success<>(balance - amount); }
static void show(Result<Integer> r) { if (r instanceof Success<Integer> s) { System.out.println("OK, new balance Rs. " + s.value()); } else if (r instanceof Failure<Integer> f) { System.out.println("Declined: " + f.error()); } }
public static void main(String[] args) { show(withdraw(5000, 1200)); show(withdraw(5000, 8000)); show(withdraw(5000, 0));
Result<Integer> r = withdraw(300, 500); System.out.println(r + " success? " + r.isSuccess() + ", balance or 300: " + r.orElse(300)); }}OK, new balance Rs. 3800 Declined: insufficient balance: Rs. 5000 available Declined: amount must be positive Failure[error=insufficient balance: Rs. 300 available] success? false, balance or 300: 300
What this code does
- The return type
Result<Integer>tells every caller that a withdrawal can fail. A failure carries its reason as a value, so the caller decides how to show it. Success<T>andFailure<T>are generic records. ThedefaultmethodsisSuccessandorElselive in the sealed interface, so every result gets them, and they can rely on there being only two kinds.
Example 3 · Results in a stream: keep going, then report
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
sealed interface Result<T> permits Success, Failure { default boolean isSuccess() { return this instanceof Success; }}
record Success<T>(T value) implements Result<T> { }
record Failure<T>(String error) implements Result<T> { }
record Admission(String name, int marks) { }
public class BatchResultDemo { static Result<Admission> parse(String line) { String[] p = line.split(","); if (p.length != 2) { return new Failure<>("'" + line + "': expected name,marks"); } try { int marks = Integer.parseInt(p[1].trim()); if (marks < 0 || marks > 100) { return new Failure<>("'" + line + "': marks out of range"); } return new Success<>(new Admission(p[0].trim(), marks)); } catch (NumberFormatException e) { return new Failure<>("'" + line + "': marks is not a number"); } }
public static void main(String[] args) { List<String> lines = List.of("Aarav, 82", "Diya, abc", "Kabir, 91", "Meera", "Ira, 140");
Map<Boolean, List<Result<Admission>>> split = lines.stream() .map(BatchResultDemo::parse) .collect(Collectors.partitioningBy(Result::isSuccess));
System.out.println("Admitted:"); split.get(true).forEach(r -> System.out.println(" " + ((Success<Admission>) r).value())); System.out.println("Errors:"); split.get(false).forEach(r -> System.out.println(" " + ((Failure<Admission>) r).error())); }}Admitted: Admission[name=Aarav, marks=82] Admission[name=Kabir, marks=91] Errors: 'Diya, abc': marks is not a number 'Meera': expected name,marks 'Ira, 140': marks out of range
What this code does
- Every line produces a value, good or bad, so the stream runs to the end. A
NumberFormatExceptionfrom a library call is caught right where it happens and turned into aFailurewith a clear message. partitioningBy(Result::isSuccess)splits the results into the two kinds. Users see every error at once instead of fixing one line, re-uploading and meeting the next.
A method like Result<Integer> withdraw(int balance, int amount) returns new Failure<>("insufficient balance") or new Success<>(balance - amount). The caller handles both kinds, usually with instanceof patterns. Small helper methods make it pleasant to use: isSuccess(), orElse(fallback), or map(f) to change the value inside a success while passing a failure along unchanged.
Optional says "maybe no value" but not why. A Result says why, which is what a user or a log needs.When to return a result type and when to throw
Return a Result when the failure is expected and the caller can do something useful with it: show a message, try another payment, skip a bad row and continue. Validation, "not found", "declined" and "out of stock" are typical.
static Result<Integer> withdraw(Integer balance, int amount) { Objects.requireNonNull(balance, "balance"); // broken input: throw if (amount > balance) { return new Failure<>("insufficient balance"); // expected: return it } return new Success<>(balance - amount);}Throw an exception when something is broken: a bug such as a null where none is allowed, a broken promise in your own code, or a failed resource like a lost database connection. The current caller usually cannot fix those, so it is right for them to travel up to a place that logs them and stops. Mixing the two, such as throwing for a wrong OTP or returning Failure for a programming bug, makes code harder to read.
Modelling API responses and order states
The same idea fits anything that is one of a few outcomes or stages. An API response can be Ok(body), NotFound(id) or Invalid(List<String> errors), each with exactly its own data. An order moves through states: Placed, Paid(txnId), Shipped(trackingId), Delivered(date) or Cancelled(reason).
Example 4 · Order states as a sealed family
import java.time.LocalDate;
sealed interface Result<T> permits Success, Failure { }
record Success<T>(T value) implements Result<T> { }
record Failure<T>(String error) implements Result<T> { }
sealed interface OrderState permits Placed, Paid, Shipped, Delivered, Cancelled { }
record Placed(String orderId) implements OrderState { }
record Paid(String orderId, String txnId) implements OrderState { }
record Shipped(String orderId, String trackingId) implements OrderState { }
record Delivered(String orderId, LocalDate on) implements OrderState { }
record Cancelled(String orderId, String reason) implements OrderState { }
public class OrderStateDemo { static Result<OrderState> ship(OrderState s, String trackingId) { if (s instanceof Paid p) { return new Success<>(new Shipped(p.orderId(), trackingId)); } else if (s instanceof Placed) { return new Failure<>("cannot ship: payment pending"); } else if (s instanceof Cancelled c) { return new Failure<>("cannot ship: cancelled (" + c.reason() + ")"); } else if (s instanceof Shipped || s instanceof Delivered) { return new Failure<>("already shipped"); } throw new AssertionError("unhandled state: " + s); }
static void tryShip(OrderState s) { Result<OrderState> r = ship(s, "DTDC-88412"); if (r instanceof Success<OrderState> ok) { System.out.println(s + " -> " + ok.value()); } else if (r instanceof Failure<OrderState> f) { System.out.println(s + " -> " + f.error()); } }
public static void main(String[] args) { tryShip(new Paid("ORD-1", "UPI-7781")); tryShip(new Placed("ORD-2")); tryShip(new Cancelled("ORD-3", "customer request")); tryShip(new Delivered("ORD-4", LocalDate.of(2025, 3, 14))); }}Paid[orderId=ORD-1, txnId=UPI-7781] -> Shipped[orderId=ORD-1, trackingId=DTDC-88412] Placed[orderId=ORD-2] -> cannot ship: payment pending Cancelled[orderId=ORD-3, reason=customer request] -> cannot ship: cancelled (customer request) Delivered[orderId=ORD-4, on=2025-03-14] -> already shipped
What this code does
- Each state holds only its own data: a transaction id exists only on
Paid, a tracking id only onShipped. An order cannot be "shipped without a tracking id", because that record cannot be built without one. - A state change returns a new record inside a
Result. Invalid moves are expected business outcomes, so they come back asFailurevalues with a reason the support team can read.
A tracking number exists only on a shipped order, so a Shipped record holds it and no other state does.
State changes become methods that return a Result: shipping a paid order succeeds with a new Shipped state; shipping a cancelled order returns a Failure with the reason. No state is ever changed in place, because each one is an immutable record.
Why the compiler can check that every case is handled
Because the family is closed, the compiler knows every kind. You can use that in Java 17 already: declare an abstract method in the sealed interface, such as <R> R fold(Function<T, R> onSuccess, Function<String, R> onFailure).
Example 5 · Java 17: let the compiler check every case with fold
import java.util.List;import java.util.function.Function;
sealed interface ApiResponse permits Ok, NotFound, Invalid { // every kind must implement this, so none can be forgotten <R> R fold(Function<Ok, R> onOk, Function<NotFound, R> onNotFound, Function<Invalid, R> onInvalid);}
record Ok(String body) implements ApiResponse { public <R> R fold(Function<Ok, R> onOk, Function<NotFound, R> onNotFound, Function<Invalid, R> onInvalid) { return onOk.apply(this); }}
record NotFound(String id) implements ApiResponse { public <R> R fold(Function<Ok, R> onOk, Function<NotFound, R> onNotFound, Function<Invalid, R> onInvalid) { return onNotFound.apply(this); }}
record Invalid(List<String> errors) implements ApiResponse { Invalid { errors = List.copyOf(errors); }
public <R> R fold(Function<Ok, R> onOk, Function<NotFound, R> onNotFound, Function<Invalid, R> onInvalid) { return onInvalid.apply(this); }}
public class FoldDemo { static int httpStatus(ApiResponse r) { return r.fold(ok -> 200, nf -> 404, inv -> 400); }
static String message(ApiResponse r) { return r.fold( ok -> ok.body(), nf -> "No student with roll " + nf.id(), inv -> String.join("; ", inv.errors())); }
public static void main(String[] args) { List<ApiResponse> responses = List.of( new Ok("{\"name\":\"Diya\",\"cgpa\":8.7}"), new NotFound("CS-404"), new Invalid(List.of("email missing", "phone must be 10 digits"))); for (ApiResponse r : responses) { System.out.println(httpStatus(r) + " " + message(r)); } }}200 {"name":"Diya","cgpa":8.7}
404 No student with roll CS-404
400 email missing; phone must be 10 digitsWhat this code does
foldtakes one function per kind, and each record calls the one that matches it. Callers never writeinstanceof, and every call must say what to do for all three kinds.- If someone adds
record Unauthorized(...) implements ApiResponse, javac refuses it until it implementsfold, and adding a fourth parameter tofoldthen breaks every caller that does not handle it. The compiler checks completeness, in Java 17.
Example 6 · Java 21: an exhaustive switch over a sealed Result
// Java 21import java.util.List;
sealed interface Result<T> permits Success, Failure { }
record Success<T>(T value) implements Result<T> { }
record Failure<T>(String error) implements Result<T> { }
public class ExhaustiveSwitchDemo { static Result<Integer> bookSeats(int available, int wanted) { if (wanted > available) { return new Failure<>("only " + available + " seats left"); } return new Success<>(available - wanted); }
static String describe(Result<Integer> r) { return switch (r) { case Success<Integer> s -> "Booked. Seats left: " + s.value(); case Failure<Integer> f -> "Not booked: " + f.error(); }; }
public static void main(String[] args) { for (int wanted : List.of(2, 9)) { System.out.println(describe(bookSeats(6, wanted))); } }}Booked. Seats left: 4 Not booked: only 6 seats left
What this code does
- Java 21:
case Success<Integer> s ->matches a type and names it, like aninstanceofpattern. Theswitchhas nodefault, becauseResultis sealed and both permitted kinds are listed. - Add a third record to
Resultand thisswitchstops compiling, reporting that it does not cover all possible input values. That is the check aninstanceofchain cannot give you.
Every record must implement it, so adding a new kind without handling it is a compile error, not a run-time surprise.
In Java 21, a switch with type patterns over a sealed type needs no default when it lists every permitted kind. If a kind is missing, javac reports that the switch does not cover all possible input values. The Pattern Matching module teaches this switch in full; the example below marks the one Java 21 program in this lesson.
Next step
Check your understanding
12 quick questions