On this page
  1. Tutorial: Modern Data Modeling with Records & Sealed Types
  2. Goal
  3. Run It Directly
  4. Complete Pure-JDK Example
  5. What This Demonstrates

Tutorial: Modern Data Modeling with Records & Sealed Types

Prev: Tutorials | Up: Tutorials | Next: Virtual Threads & HTTP Client
Rel: Classes, Records & Sealed Hierarchies, record, sealed, switch expressions
Ref: Java 21 Language Guide , Dev.java
Tags: #public #java #tutorial #data-modeling #tier/core


Goal

Build a self-contained, zero-dependency Java 21 program that models a small expression evaluator and validation result using sealed interface, record, and exhaustive pattern-matching switch with guards.

Run It Directly

Save as ExpressionDemo.java and run with OpenJDK 21+:

java ExpressionDemo.java

Complete Pure-JDK Example

import java.util.List;

public class ExpressionDemo {

    // 1. Closed AST using a sealed interface + immutable records
    sealed interface Expr permits Num, Add, Mul, Div {}
    record Num(double value) implements Expr {}
    record Add(Expr left, Expr right) implements Expr {}
    record Mul(Expr left, Expr right) implements Expr {}
    record Div(Expr left, Expr right) implements Expr {}

    // 2. Closed evaluation result (avoids throwing exceptions for expected math errors)
    sealed interface EvalResult permits Ok, Err {}
    record Ok(double value) implements EvalResult {}
    record Err(String message) implements EvalResult {}

    static EvalResult eval(Expr expr) {
        return switch (expr) {
            case Num(double v) -> new Ok(v);
            case Add(var l, var r) -> combine(eval(l), eval(r), Double::sum);
            case Mul(var l, var r) -> combine(eval(l), eval(r), (a, b) -> a * b);
            case Div(var l, var r) -> switch (eval(r)) {
                case Err e -> e;
                case Ok(double denom) when denom == 0.0 -> new Err("Division by zero");
                case Ok(double denom) -> switch (eval(l)) {
                    case Err e -> e;
                    case Ok(double num) -> new Ok(num / denom);
                };
            };
        };
    }

    @FunctionalInterface
    interface DoubleOp {
        double apply(double a, double b);
    }

    static EvalResult combine(EvalResult left, EvalResult right, DoubleOp op) {
        if (left instanceof Err e) return e;
        if (right instanceof Err e) return e;
        return new Ok(op.apply(((Ok) left).value(), ((Ok) right).value()));
    }

    static String format(EvalResult result) {
        return switch (result) {
            case Ok(double v) -> "Result = " + v;
            case Err(String msg) -> "Error: " + msg;
        };
    }

    public static void main(String[] args) {
        List<Expr> samples = List.of(
            new Add(new Num(10), new Mul(new Num(2), new Num(5))),
            new Div(new Num(42), new Num(0))
        );

        for (Expr expr : samples) {
            System.out.println(expr + " -> " + format(eval(expr)));
        }
    }
}

What This Demonstrates

Linked from

Related notes