A closed record hierarchy

A sealed interface implemented by a group of records is the modern shape of a value model: a fixed set of forms, each carrying exactly its data, and functions that a switch on the interface can cover completely. The compiler knows the whole set, so a function that forgets one form does not build, and a function that adds a default gives that guarantee up on purpose.

The hierarchy

Value is one of four things: a number, a text, a boolean or the absence of one. Each form is a record, so each carries its payload and the compiler writes its equals and toString. The interface names them and nothing else, which is the permits clause of lesson 058:

public class Values { public static void main(String[] args) { Value[] values = {new Num(42), new Text("hi"), new Bool(true), new None()}; for (Value value : values) { System.out.println(value + " -> " + render(value)); } } static String render(Value value) { return switch (value) { case Num(int n) -> Integer.toString(n); case Text(String text) -> '"' + text + '"'; case Bool(boolean b) -> Boolean.toString(b); case None() -> "null"; }; } } sealed interface Value permits Num, Text, Bool, None { } record Num(int value) implements Value { } record Text(String value) implements Value { } record Bool(boolean value) implements Value { } record None() implements Value { }

javac -Xlint:all Values.java
java Values

Num[value=42] -> 42
Text[value=hi] -> "hi"
Bool[value=true] -> true
None[] -> null

None() is a record with no components, and its toString is None[]: the pattern also has empty parentheses, because a record pattern mirrors the declaration. The left column is the generated toString and the right one is the function, which is the distinction a value model lives on.

A total function

A function with a case per form and no default is total over the type: for every value that can exist, a case matches. That is what the compiler proves here, and it is stronger than a default that answers "unknown", because the unknown case cannot be reached and a new form cannot slip into it unnoticed.

The cost appears when the model grows. Adding a form is a change to the interface and to every total function, and the compiler lists the functions by refusing to build them. That is the trade a closed hierarchy makes: local ease of adding data against a compile error at every reader. An open interface makes the opposite trade, and then a default is the only way to write the function.

The case that goes missing

Delete the None case and the function stops building. The message is the one of lesson 060 and does not name the missing form; what it says is that the coverage is incomplete, and the permits clause above the switch is where a reader looks:

public class Missing { public static void main(String[] args) { System.out.println(render(new None())); } static String render(Value value) { return switch (value) { case Num(int n) -> "num"; case Text(String s) -> "text"; case Bool(boolean b) -> "bool"; }; } } sealed interface Value permits Num, Text, Bool, None { } record Num(int value) implements Value { } record Text(String value) implements Value { } record Bool(boolean value) implements Value { } record None() implements Value { }

javac -Xlint:all Missing.java

Missing.java:7: error: the switch expression does not cover all possible input values
return switch (value) {
^
1 error

The caret is on the switch, which is where the check happens. In a file of twenty classes the missing form is not obvious from the message, so a value model keeps its records in one small file, or one file per record and the interface beside them.

A recursive model

A component may have the interface type, so a record can hold other records of the same hierarchy. An expression tree is the standard case: a literal, an addition of two expressions and a multiplication of two. Both functions are recursive, and both are total:

public class Exprs { public static void main(String[] args) { Expr[] exprs = { new Lit(7), new Add(new Lit(2), new Lit(3)), new Mul(new Add(new Lit(1), new Lit(2)), new Lit(4)), }; for (Expr expr : exprs) { System.out.println(show(expr) + " = " + eval(expr)); } } static int eval(Expr expr) { return switch (expr) { case Lit(int value) -> value; case Add(Expr left, Expr right) -> eval(left) + eval(right); case Mul(Expr left, Expr right) -> eval(left) * eval(right); }; } static String show(Expr expr) { return switch (expr) { case Lit(int value) -> Integer.toString(value); case Add(Expr left, Expr right) -> "(" + show(left) + " + " + show(right) + ")"; case Mul(Expr left, Expr right) -> "(" + show(left) + " * " + show(right) + ")"; }; } } sealed interface Expr permits Lit, Add, Mul { } record Lit(int value) implements Expr { } record Add(Expr left, Expr right) implements Expr { } record Mul(Expr left, Expr right) implements Expr { }

javac -Xlint:all Exprs.java
java Exprs

7 = 7
(2 + 3) = 5
((1 + 2) * 4) = 12

A record pattern on Add(Expr left, Expr right) binds two values of the interface type, which the same switch then handles: that is the record pattern of lesson 056 and the recursion of lesson 019 in one program. A fourth node such as Neg(Expr inner) would break both functions until both learned it, which is the model working as designed.

A report over the hierarchy

Two functions, a total sum and a sort with a lambda comparator, produce a small report. The shapes are records with a different number of components, and the switch is the only place that knows which:

import java.util.Arrays; public class Shapes { public static void main(String[] args) { Shape[] shapes = {new Rect(2, 3), new Circle(1), new Rect(1, 1)}; double total = 0; for (Shape shape : shapes) { System.out.printf("%-16s %7.2f%n", name(shape), area(shape)); total += area(shape); } System.out.printf("total %.2f%n", total); Arrays.sort(shapes, (a, b) -> Double.compare(area(a), area(b))); System.out.println(name(shapes[0]) + " is the smallest"); } static double area(Shape shape) { return switch (shape) { case Rect(double w, double h) -> w * h; case Circle(double r) -> Math.PI * r * r; }; } static String name(Shape shape) { return switch (shape) { case Rect(double w, double h) -> "rect " + w + "x" + h; case Circle(double r) -> "circle r=" + r; }; } } sealed interface Shape permits Rect, Circle { } record Rect(double width, double height) implements Shape { } record Circle(double radius) implements Shape { }

javac -Xlint:all Shapes.java
java Shapes

rect 2.0x3.0 6.00
circle r=1.0 3.14
rect 1.0x1.0 1.00
total 10.14
rect 1.0x1.0 is the smallest

The total is 6 + 3.1415 + 1 = 10.1415, printed as 10.14 by the %.2f of lesson 026. The sort uses a lambda comparator, which is lesson 076, and it works because area is total: every element can be measured.

Exercises

  1. Add a Neg(Expr inner) record to Exprs and make both functions handle it; the value of the new node is minus its inner value.
  2. Add a Text case to the name function of Shapes and see which other functions stop building.
  3. Give Value a method isNull() with a default body that asks the switch.
  4. Print the shapes again after the sort and check that the order is the one the comparator gives.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What makes a function over a sealed hierarchy total?

    Answer

    A case for every permitted subtype and no default

    The compiler knows the permitted set, so a complete switch covers every value that can exist.

  2. What does adding a record to the hierarchy do to a total function?

    Answer

    It stops compiling until the new form has a case

    That compile error is the property the closed hierarchy is chosen for.

  3. Why is None() a record with empty parentheses?

    Answer

    It has no components, and a record pattern mirrors the declaration

    The pattern must match the component list, and this record has none.

  4. What does this program print? public class Q1 { public static void main(String[] args) { V[] values = {new N(1), new T("a")}; for (V value : values) { System.out.print(text(value) + " "); } } static String text(V value) { return switch (value) { case N(int n) -> "n" + n; case T(String s) -> "t" + s; }; } } sealed interface V permits N, T { } record N(int n) implements V { } record T(String s) implements V { }

    Answer

    n1 ta

    Each record pattern binds its component and the two results print in array order.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(render(new Num(0))); } static String render(Value v) { return switch (v) { case Num(int n) when n == 0 -> "zero"; case Num(int n) -> "number"; case None() -> "none"; }; } } sealed interface Value permits Num, None { } record Num(int value) implements Value { } record None() implements Value { }

    Answer

    zero

    The guard accepts the zero, and the unguarded Num case takes the rest.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println(eval(new Add(new Lit(2), new Lit(3)))); } static int eval(Expr e) { return switch (e) { case Lit(int v) -> v; case Add(Expr a, Expr b) -> eval(a) + eval(b); }; } } sealed interface Expr permits Lit, Add { } record Lit(int value) implements Expr { } record Add(Expr left, Expr right) implements Expr { }

    Answer

    5

    The nested records bind two literal values, and the sum is five.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { System.out.println(text(new B())); } static String text(V v) { return switch (v) { case A() -> "a"; }; } } sealed interface V permits A, B { } record A() implements V { } record B() implements V { }

    Answer

    error: the switch expression does not cover all possible input values

    B is permitted but has no case, so the switch is not exhaustive.

  8. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(new N(2) + " " + name(new N(2))); } static String name(V v) { return switch (v) { case N(int n) -> "n" + n; }; } } sealed interface V permits N { } record N(int n) implements V { }

    Answer

    N[n=2] n2

    The generated toString and the function answer differently, which is the point of a model.

  9. Why does the report sort work on a sealed hierarchy?

    Answer

    The area function is total, so every element can be measured

    The lambda calls a total function, which every permitted subtype answers.

  10. What does a default in a total function give up?

    Answer

    The compile error that a new form would cause

    A default catches the new form silently, so the compiler cannot force a decision about it.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev