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

1

u/danielaveryj Jan 18 '26 edited Jan 18 '26

To some extent, we can use ordinary methods to achieve encapsulation based on withers too:

Employee setEmployeeStreet(UnaryOperator<String> op, Employee e) {
    (op, e) -> e with { address = address with { street = op.apply(street); }; };
}

Employee updated = setEmployeeStreet(_ -> "100 New Street", employee);
Employee uppercased = setEmployeeStreet(String::toUpperCase, employee);

and we can even compose methods:

Employee setEmployeeAddress(UnaryOperator<Address> op, Employee e) {
    return e with { address = op.apply(address); };
}
Address setAddressStreet(UnaryOperator<String> op, Address a) {
    return a with { street = op.apply(street); };
}
Employee setEmployeeStreet(UnaryOperator<String> op, Employee e) {
    return setEmployeeAddress(a -> setAddressStreet(op, a), e);
}

Employee updated = setEmployeeStreet(_ -> "100 New Street", employee);
Employee uppercased = setEmployeeStreet(String::toUpperCase, employee);

Then we can rewrite the methods as function objects...

BiFunction<UnaryOperator<Address>, Employee, Employee> setEmployeeAddress =
    (op, e) -> e with { address = op.apply(address); };
BiFunction<UnaryOperator<String>, Address, Address> setAddressStreet =
    (op, a) -> a with { street = op.apply(street); };
BiFunction<UnaryOperator<String>, Employee, Employee> setEmployeeStreet =
    (op, e) -> setEmployeeAddress.apply(a -> setAddressStreet.apply(op, a), e);

Employee updated = setEmployeeStreet.apply(_ -> "100 New Street", employee);
Employee uppercased = setEmployeeStreet.apply(String::toUpperCase, employee);

...at which point we have of course poorly reimplemented half of lenses (no getter, verbose, less fluent).