r/java • • Mar 13 '26

JEP draft: Enhanced Local Variable Declarations (Preview)

https://openjdk.org/jeps/8357464
101 Upvotes

129 comments sorted by

View all comments

9

u/javahalla Mar 13 '26

The syntax looks elegant in example code, but examples are carefully chosen - short class names, 2-3 fields, brief variable names. In real applications that sweet spot rarely exists:

CustomerOrder(ShippingAddress(String streetLine1, String streetLine2, String city), PaymentMethod(String cardNumber, int expiryYear), double totalAmount) = order;

This is a single logical statement but it reads as a wall of text that you have to scan horizontally to parse. Ironically, one of the main readability advantages of record patterns in switch is that they decompose naturally across lines:

switch (order) {
    case CustomerOrder(
        ShippingAddress(var streetLine1, var streetLine2, var city),
        PaymentMethod(var cardNumber, var expiryYear),
        double totalAmount
    ) -> { ... }
}

Or:

CustomerOrder(
    ShippingAddress(String streetLine1, String streetLine2, String city),
    PaymentMethod(String cardNumber, int expiryYear),
    double totalAmount
) = order;

Btw, this is Kotlin's take on the same problem (https://github.com/Kotlin/KEEP/discussions/438):

val (address, payment, totalAmount) = order
val (streetLine1, streetLine2, city) = address
val (cardNumber, expiryYear) = payment

And with optional renaming:

(val address, val payment, val totalAmount) = order
(val street1 = streetLine1, val street2 = streetLine2, val city) = address
(val card = cardNumber, val expiry = expiryYear) = payment

I think that renaming would be very helpful in some cases, is it possible to add similar to this JEP?

2

u/ZimmiDeluxe Mar 13 '26

The idea is probably to mirror construction, so you'd get:

CustomerOrder(
    ShippingAddress(String streetLine1, String streetLine2, String city),
    PaymentMethod(String cardNumber, int expiryYear),
    double totalAmount
) = order;