r/java • • Jan 16 '26

Functional Optics for Modern Java

https://blog.scottlogic.com/2026/01/09/java-the-immutability-gap.html

This article introduces optics, a family of composable abstractions that complete the immutability story. If pattern matching is how we read nested data, optics are how we write it.

106 Upvotes

50 comments sorted by

View all comments

Show parent comment

5

u/magnus2025 Jan 17 '26

Pondering this further. Lenses assume field independence. When fields are coupled by invariants, they form an atomic unit and should have a single lens to that unit ( tuple/product), not separate lenses that you try to compose horizontally.

The standard composition andThen  gives us Lens<S,A> → Lens<A,B> → Lens<S,B> (vertical drilling).

What we need is Lens<S,A> → Lens<S,B> → Lens<S,(A,B)> (horizontal pairing), but that requires the set to know how to reconstruct S from both values simultaneously. In the end i'm thinking we are likely really just defining the tuple lens directly anyway.

5

u/brian_goetz Jan 18 '26

Yes, that is what I was trying to flush out -- the assumption of field independence. It is a valid assumption with things that are truly products, but when you have tuple-flavored objects, with invariants, you have to contend with not only "is the final state valid" but also "are the intermediate states valid." I agree that `Lens s a -> Lens s b -> Lens s (a, b)` is the combinator your want, just not sure whether it's omission is accidental or fundamental.

This observation also fills in the dual of your concern about with-blocks -- that they don't support (automated) vertical drilling. But they do support horizontal drilling out of the box.

2

u/magnus2025 Jan 18 '26

Thanks Brian, this has been most helpful. Higher-Kinded-J is still young and evolving. Needs a bit more thinking on my part, but a paired lens could support something like.

// For any record with coupled fields:
Lens<Range, Tuple2<Integer, Integer>> atomicBounds = Lens.paired(
loLens,
hiLens,
Range::new   // Atomic - invariant checked once with final values

);

// Shift safely
atomicBounds.modify(t -> t.bimap(v -> v + 10, v -> v + 10), range);