Functional Optics for Modern Java (opens in new tab)

blog.scottlogic.com·12w·Open original (opens in new tab)

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:

  1. Type-safe: The compiler catches structural errors
  2. Immutable: Expressions never change; transformations produce new trees
  3. Transformable: Easy to analyse, optimise, and rewrite
Loading more...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Save / unsave
s
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help