Optics in Practice: An Expression Language AST
Part 3 of the Functional Optics for Modern Java series
In Part 1 and Part 2, we established why optics matter and how they work. Now it’s time to apply them to a real domain by building an expression language interpreter.
Expression languages are the backbone of modern Java infrastructure, from Spring Expression Language (SpEL) to rule engines like Drools. If you’ve ever configured a complex Spring application or written business rules, you’ve used one. In this article we will show how Java 25’s data-oriented programming features, combined with Higher-Kinded-J optics, make building such systems remarkably clean.
This is a domain where optics really shine.
Over the next three articles, we’ll build a complete expression language with parsing, type checking, optimisation, and interpretation. Along the way, you’ll see how optics transform what would otherwise be tedious tree manipulation into elegant, composable operations.
Running the Examples
Article Code
All code examples from this article have runnable demos:
- ExprDemo: Building ASTs, using prisms, and Focus DSL composition
- OptimiserDemo: Constant folding, identity simplification, and complex optimisation
The AST types are defined in org.higherkindedj.article3.ast, with transformations in org.higherkindedj.article3.transform.
The Expression Language Domain
What exactly are we building? A small but powerful expression language suitable for:
- Configuration expressions:
if (env == "prod") then timeout * 2 else timeout - Rule engines:
price > 100 && customer.tier == "gold" - Template systems:
"Hello, " + user.name + "!" - Domain-specific calculations:
principal * (1 + rate) ^ years
The language will support:
- Literal values (integers, booleans, strings)
- Variables with lexical scoping
- Binary operations (arithmetic, comparison, logical)
- Conditional expressions (if-then-else)
Our design goals are:
- Type-safe: The compiler catches structural errors
- Immutable: Expressions never change; transformations produce new trees
- Transformable: Easy to analyse, optimise, and rewrite