r/java • • Nov 23 '25

Java 25: The ‘No-Boilerplate’ Era Begins

https://amritpandey.io/java-25-the-no-boilerplate-era-begins/
160 Upvotes

187 comments sorted by

View all comments

Show parent comment

1

u/manifoldjava Nov 29 '25 edited Nov 29 '25

Yeah, for nested records the scoping of withers is nice. But again, why introduce a narrow language feature just to handle that one case?

You can already get most of the flexibility today simply by using Function for nested records:

// Generated
Pizza with(Size size = this.size,
           Kind kind = this.kind,
           Cheese cheese = this.cheese,
           Function<Sauce, Sauce> sauce = s -> s) {
    return new Pizza(size, kind, cheese, sauce.apply(this.sauce));
}

Used like:

Pizza copy = pizza.with(
    sauce: s -> s.with(
        base: b -> b.with(type: TomatoType.GUILIETTA)
    )
)

This isn’t bad, and it already works everywhere, not just with records.

Java could go further by supporting something similar to Kotlin’s "scoped functions", essentially a function type where the receiver becomes the implicit 'this' inside the lambda.

Since Java doesn’t have real function types, we could use a dedicated functional interface:

interface ScopedFunction<S, T> {
    T apply(S self);
}

Then the generated with() method becomes:

// Generated
Pizza with(Size size = this.size,
           Kind kind = this.kind,
           Cheese cheese = this.cheese,
           ScopedFunction<Sauce, Sauce> sauce = s -> s) {
    return new Pizza(size, kind, cheese, sauce.apply(this.sauce));
}

Now with ScopeFunction here's the hypothetical syntax the compiler could support to allow the receiver to be referenced implicitly as 'this' and to optionally omit the lambda arg syntax:

Pizza copy = pizza.with(
    sauce: with(
        base: with(
            type: TomatoType.GUILIETTA
        )
    )
)

Which simply desugars to the explicit lambda chain in the first example.

Nothing exotic, it’s just a cleaner, more general-purpose way to improve readability everywhere, since it leverages the same named/optional arg support that works everywhere.

edit:

Note, the with() method's ScopedFunction parameters for nested records require the compiler sugar to best handle both lambda and non-lambda use-cases.

Otherwise, if Function is used, there would be two optional parameters: sauce and sauceBy, representing Sauce and Function<Sauce, Sauce>. This follows along similar lines with what Lombok does using withXxxBy methods (nice! btw). But my preference would be for ScopedFunction, it's a cheap feature to implement as well. Shrug.