Sub topic 9
Sealed Types with Generics
This chapter assumes you understand Java interfaces, inheritance, records, switch expressions, and basic generic types. Java sealed types work with type parameters, so you can restrict both the set of implementations and the kind of data those implementations carry.
Combining `sealed` with a type parameter
A generic sealed interface declares one fixed family of implementations for every type argument:
sealed interface Result<T> permits Ok, Err {
}
record Ok<T>(T value) implements Result<T> {
}
record Err<T>(String message) implements Result<T> {
}Result<T> has one type parameter, T. Ok<T> stores a successful value of type T, while Err<T> stores an error message.
The permits clause applies to the generic type declaration itself. It permits the Ok and Err class declarations. For example, Ok<Integer> and Ok<String> are different parameterizations of the same permitted subtype. They do not become separate permitted classes.
flowchart TD
R["Result<T>"]
O["Ok<T>"]
E["Err<T>"]
R --> O
R --> E
O --> OI["Ok<Integer>"]
O --> OS["Ok<String>"]
E --> EI["Err<Integer>"]
E --> ES["Err<String>"]Exhaustive switches over a generic sealed type
A selector can use a specific type argument, such as Result<Integer>. The switch still needs to handle each permitted implementation.
public class GenericSealedDemo {
sealed interface Result<T> permits Ok, Err {
}
record Ok<T>(T value) implements Result<T> {
}
record Err<T>(String message) implements Result<T> {
}
static String describe(Result<Integer> result) {
return switch (result) {
case Ok<?> ok -> "value " + ok.value();
case Err<?> err -> "error " + err.message();
};
}
public static void main(String[] args) {
System.out.println(describe(new Ok<>(42)));
System.out.println(describe(new Err<>("Missing value")));
}
}The <?> is an unbounded wildcard. It means that the pattern accepts an Ok or Err whose type argument is unknown. The selector already guarantees that the result is a Result<Integer>, so these two cases cover all possible implementations.
The switch has no default branch. The compiler can prove that Result has only the permitted subtypes Ok and Err.
In many cases, writing the wildcard patterns is more practical than trying to expose the exact type argument inside the pattern. The value returned by ok.value() has an unknown capture type, but it can still be printed or passed to code that accepts Object.
> callout note > Generic arguments do not create new subclasses. Ok<Integer> and Ok<String> are instances of the same permitted record declaration, Ok<T>.
Generic sealed types and invariance
Java generic types are invariant. An Ok<Integer> is not an Ok<Number>, even though Integer is a subtype of Number.
Ok<Integer> integerResult = new Ok<>(42);
// Ok<Number> numberResult = integerResult; // Does not compileUse a wildcard when you need to accept results with different type arguments:
static void printResult(Result<?> result) {
switch (result) {
case Ok<?> ok -> System.out.println("value: " + ok.value());
case Err<?> err -> System.out.println("error: " + err.message());
}
}Result<?> means “a result containing some type, but the exact type is not important here.” You can read the value as an Object, but you cannot safely insert an arbitrary value into it.
Choosing the type parameter
A generic sealed hierarchy is useful when every variant follows the same type relationship:
| Design | Example | Best fit |
|---|---|---|
| Generic variants | `Result<T>` | Success and failure share a result type |
| Different data shapes | `Expr` with `Num`, `Add`, and `Mul` | Each variant has its own fields |
| Fixed constants | `enum Status` | A small set of named values with no type parameter |
Use an ordinary sealed hierarchy when the variants need unrelated data types. Use a generic sealed hierarchy when the same type parameter should remain consistent across the family.
Exercise
Why does Result<?> use a wildcard instead of Result<Object>?
Show answer
Result<?> accepts a Result with any type argument. Result<Object> accepts only a Result<Object>, because Java generics are invariant.