#2368·lombok

[FEATURE] @WithBy support (with, but with lambdas)

Author: rzwitserlootCreated Feb 13, 2020Updated Sep 1, 2026

We already have @With. However, if you have hierarchical immutable data structures, it is unwieldy. Example:

java
@Value class Movie { @With Director director; }
@Value class Director { @With LocalDate dob; }

to modify the name of the director given a movie variable, you'd have to do: movie.withDirector(movie.getDirector().withDob(movie.getDirector().getDob().withYear(1999))); – add more levels of nesting and it gets a lot longer.

Proposal

lombokized:

java
@Value class Movie { @WithBy Director director; }
@Value class Director { @WithBy LocalDate db; }

generating:

java
public Movie withDirectorBy(UnaryOperator<Director> mapper) {
    return new Movie(mapper.apply(this.getDirector()));
}

Why?

Well, compare:

java
movie.withDirector(movie.getDirector().withDob(movie.getDirector().getDob().withYear(1999)));

movie.withDirectorBy(d -> d.withDobBy(b -> b.withYear(1999)));

as this is a bit of an experiment (using lombok to establish novel new idioms), let's start this one in the experimental package.

NB: Intentional choice to go with the withXBy naming scheme; we could just do withX just like @With does, and the 2 generated methods don't really clash in the sense that I expect having a field of type UnaryOperator is exceedingly rare, however, by having two equally named methods that both take a single reference, withX(null) would then be a compile time error (ambiguous invocation). To avoid that, we use a different name.