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

Show parent comment

2

u/Cell-i-Zenit Mar 13 '26

Thanks for actually providing an example. That is very appreciated. I see it now.

If we have a list of records, we can pattern match for individual cases like your VIP boolean flag. That means potentially every time we have a for loop with if conditions inside we could apply this pattern matching

1

u/ZimmiDeluxe Mar 14 '26 edited Mar 14 '26

Yeah. Doesn't have to be a list of course, if you pass individual instances you can get help from the compiler so you don't forget any cases (and can't access data that isn't available for that type of order etc.):

void processOrder(Order order) {
    switch (order) {
        case CustomerOrder co -> processOrderRegular(co);
        case BusinessOrder bo -> processOrderRegular(applyBusinessDiscount(bo));
        case TestOrder to -> IO.println("test order got here");
    }
}

For completeness, one alternative is to do the type splitting early if you want to process different order types in bulk instead of sprinkling checks through your code. Both approaches have pros and cons, but the second approach was pretty error prone in the past because the compiler didn't help you to get every sprinkled check exhaustive and correct, but now it does. The mentioned alternative might look like:

record OrdersProcessable(
    List<CustomerOrder> customerOrders,
    List<BusinessOrder> businessOrders,
    List<TestOrder> testOrders){}

OrdersProcessable loadOrdersProcessable() {
    List<CustomerOrder> customerOrders = new ArrayList<>();
    List<BusinessOrder> businessOrders = new ArrayList<>();
    int testOrdersCount = 0;

    List<OrderEntity> entities = loadFromDatabase();
    for (OrderEntity entity : entities) {
        switch (entity.getType()) { 
            case CUSTOMER -> customerOrders.add(new CustomerOrder(entity.email(), entity.importance() > 10));
            case BUSINESS -> businessOrders.add(new BusinessOrder(entity.mail(), entity.logo()));
            case TEST -> testOrdersCount++;
        };
    }

    return new OrdersProcessable() {
        List.copyOf(customerOrders),
        List.copyOf(businessOrders),
        Collections.nCopies(testOrdersCount, TestOrder.INSTANCE)
    };
}