Sub topic 9
Sealed Types with Generics
Sealed types and generics work together. A sealed interface can have type parameters, its permitted subclasses can pass those parameters through or fix them, and the compiler uses that information when it checks a switch for exhaustiveness. This chapter covers the syntax, the exhaustiveness behavior and the errors you are most likely to hit.
This chapter assumes you know the sealed, permits, final and non-sealed keywords from earlier chapters. It also assumes you know records, switch expressions, and basic generics (type parameters, wildcards and erasure). Pattern matching for switch and record patterns need Java 21 or later.
A generic sealed interface
The most common use is a "result" type with two variants: a success that carries a value and a failure that carries a message.
import java.util.function.Function;
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String message) implements Result<T> {}
public class Main {
static Result<Integer> parse(String text) {
try {
return new Ok<>(Integer.parseInt(text));
} catch (NumberFormatException e) {
return new Err<>("not a number: " + text);
}
}
static <T, R> Result<R> map(Result<T> result, Function<? super T, ? extends R> f) {
return switch (result) {
case Ok<T>(T value) -> new Ok<>(f.apply(value));
case Err<T>(String message) -> new Err<>(message);
};
}
static String describe(Result<Integer> r) {
return switch (r) {
case Ok<Integer> ok -> "value " + ok.value();
case Err<Integer> err -> "error " + err.message();
};
}
public static void main(String[] args) {
System.out.println(describe(map(parse("21"), n -> n * 2)));
System.out.println(describe(map(parse("x"), n -> n * 2)));
}
}This prints value 42 and then error not a number: x.
Three details matter here.
- The
permitsclause names raw class names. You writepermits Ok, Err, neverpermits Ok<T>, Err<T>. - Each permitted subclass must still be a subtype of
Result<T>for some type argument. HereOk<T> implements Result<T>passes the parameter straight through. maphas nodefaultbranch. The two cases coverOkandErr, and nothing else can implementResult.
How a permitted subclass can use the type parameter
A permitted subclass has three options for the parent's type parameter.
| Option | Example | Effect |
|---|---|---|
| Pass it through | `record Ok<T>(T value) implements Result<T>` | The subclass is generic in the same way as the parent. |
| Fix it | `record IntBox(int value) implements Box<Integer>` | The subclass exists only for one type argument. |
| Add parameters | `record Tagged<T, M>(T value, M meta) implements Result<T>` | The subclass has more type parameters than the parent. |
You can also leave a parameter unused in the subclass's own components. In Err<T>, the T is not stored in any field. It exists so that an Err<Integer> is a Result<Integer>. A type parameter used only to link a type to its parent is called a phantom parameter. It is common in result and option types.
Exhaustiveness and type arguments
Fixing the type argument in a subclass has a useful consequence. When the compiler checks exhaustiveness, it considers only the permitted subclasses that could actually be instances of the static type. A subclass that can never match is left out of the check.
sealed interface Box<T> permits IntBox, StrBox {}
record IntBox(int value) implements Box<Integer> {}
record StrBox(String text) implements Box<String> {}
public class Main {
static String read(Box<String> box) {
return switch (box) {
case StrBox s -> s.text();
};
}
public static void main(String[] args) {
System.out.println(read(new StrBox("hello")));
}
}This compiles and prints hello. A Box<String> cannot be an IntBox, because IntBox is a Box<Integer> and Box<Integer> and Box<String> are unrelated types. The compiler therefore needs only the StrBox case. If you add case IntBox i, the compiler rejects it as an impossible conversion from Box<String> to IntBox.
The same rule applies when a generic subclass fixes the parameter in a more complex way. JEP 409 gives this pattern:
sealed interface I<T> permits A, B {}
final class A<X> implements I<String> {}
final class B<Y> implements I<Y> {}A switch over I<Integer> needs only a case for B. A always implements I<String>, so it cannot appear. A switch over I<String> needs both.
Record patterns with generic records
Record patterns work on generic records. You can write the type arguments or let the compiler infer them.
static String show(Result<Integer> r) {
return switch (r) {
case Ok<Integer>(Integer v) -> "ok " + (v + 1);
case Err<Integer>(var message) -> "err " + message;
};
}
static String showInferred(Result<Integer> r) {
return switch (r) {
case Ok(var v) -> "ok " + (v + 1);
case Err(var message) -> "err " + message;
};
}In showInferred, the compiler infers Ok<Integer> from the selector type Result<Integer>, so v is an Integer. Inference is convenient. Writing the type arguments makes the code easier to read when several generic types are in play, so choose the form that is clearer in context.
Wildcards and the selector type
If the selector has a wildcard type, you can still write an exhaustive switch. The binding types become capture types, and you can read them only as their upper bound.
static String show(Result<?> r) {
return switch (r) {
case Ok<?> ok -> "ok: " + ok.value();
case Err<?> err -> "err: " + err.message();
};
}Here ok.value() has type Object. You cannot write case Ok<Integer> ok for a Result<?> selector. That pattern would need an unchecked cast, and the compiler rejects patterns that need one.
Use a wildcard selector for code that handles any result, such as logging. Use a concrete type argument, as in Result<Integer>, when you need the value.
Sealed hierarchies with bounded parameters
A type parameter can have a bound, and permitted subclasses must respect it.
sealed interface Shape<N extends Number> permits Sized, Unsized {}
record Sized<N extends Number>(N size) implements Shape<N> {}
record Unsized<N extends Number>() implements Shape<N> {}If a subclass declared Sized<N> without the bound, the compiler would reject implements Shape<N>, because N would not satisfy Shape's bound. This is ordinary generics, but it is easy to forget when you add a bound to a hierarchy that already has subclasses.
Generics and reflection
Reflection sees the erased classes. Result.class.getPermittedSubclasses() returns Class<?>[] containing Ok.class and Err.class, with no type arguments. If you need the generic information, use getGenericInterfaces() on a permitted subclass. It returns Result<T> for Ok and Result<T> for Err, where each T is the subclass's own type variable.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `permits Ok<T>` does not compile | `permits` takes class names, not parameterized types | Write `permits Ok, Err`. |
| A permitted class "does not extend or implement" the sealed type | The subclass lists the parent with incompatible arguments, or does not list it at all | Add `implements Result<T>` (or a valid argument) to the subclass. |
| Switch over `Box<String>` rejects `case IntBox` | `IntBox` can never be a `Box<String>` | Remove the case. Only possible subclasses need one. |
| Switch over `Result<?>` rejects `case Ok<Integer>` | The pattern needs an unchecked cast | Use `Ok<?>`, or change the selector type. |
| Switch is "not exhaustive" after adding a class | A new permitted subclass can match the selector type | Add a case for it. |
| `MatchException` at runtime | An unchecked cast put an impossible subtype into a variable | Remove the cast, or validate the value before you cast it. |
Evolving a generic sealed type
When you add a permitted subclass, every switch that is exhaustive without a default can stop compiling. With generics, the effect depends on the type arguments. Suppose you add record BoolBox(boolean flag) implements Box<Boolean>. A switch over Box<String> still compiles, because BoolBox cannot be a Box<String>. A switch over Box<Integer> also still compiles. A switch over Box<?> or a raw Box<T> breaks, because the new class can match it.
If you add record Label(String text) implements Box<String> instead, the switch over Box<String> breaks, and that is what you want. The compiler lists the places that need a new case.
Exercise
Write a sealed generic type Option<T> with two records, Some<T> (holding a T value) and None<T>. Then write a method static <T> T getOrElse(Option<T> option, T fallback) that uses an exhaustive switch with no default.
Show answer
sealed interface Option<T> permits Some, None {} then record Some<T>(T value) implements Option<T> {} and record None<T>() implements Option<T> {}. The method body is return switch (option) { case Some<T>(T value) -> value; case None<T> none -> fallback; }; The switch needs no default because Some and None are the only permitted subclasses of Option, and both can match an Option<T>.
Exercise
A sealed interface Box<T> permits IntBox (implements Box<Integer>) and StrBox (implements Box<String>). A method takes a Box<String> and switches over it with only case StrBox s. Why does this compile? What happens to the switch if you add record Label(String text) implements Box<String> and list it in permits?
Show answer
It compiles because IntBox implements Box<Integer>, which can never be a Box<String>, so the compiler does not require a case for it. After you add Label, which can be a Box<String>, the switch is no longer exhaustive and fails to compile until you add a case for Label.