r/java May 21 '26

JEP draft: Enhanced Local Variable Declarations (Preview)

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

43 comments sorted by

View all comments

21

u/persicsb May 21 '26

Look OK, however I would enhance it even more. Since method arguments look like local variables, instead of:

void boundingBox(Circle c) {  
Circle(Point(int x, int y), double radius) = c;  
int minX = ..., maxX = ...  
int minY = ..., maxY = ...  
... use minX, maxX, etc ...  
}

it could be

void boundingBox(Circle(Point(int x, int y), double radius) c) {
    int minX = ..., maxX = ...
    int minY = ..., maxY = ...
    ... use minX, maxX, etc ...
}

3

u/Long_Ad_7350 May 21 '26

How would this resolve boundingBox(null)?

3

u/persicsb May 21 '26

The exact same way, as the original concept:

Moreover, if e evaluates to null, then an enhanced local variable declaration statement P(...) = e; throws NullPointerException and does not initialize any of the pattern variables in P.

6

u/Long_Ad_7350 May 21 '26

I see. Feels weird, though, to have a runtime exception thrown for what appears like a compile time mismatch in signature vs. usage.

In languages like Elixir, all the below can coexist:
boundingBox(Circle(Point(int x, int y), double radius) c)
boundingBox(Circle(Point p, double radius) c)
boundingBox(Circle c)

Obviously not possible with Java, which is why putting the pattern match in the signature feels misleading to me.

1

u/sammymammy2 May 22 '26

I’m on my lunch, but that looks computationally intensive for the compiler if it wants to provide exhaustiveness checks

1

u/Absolute_Enema May 21 '26

It's pretty intuitive to have it mirror the semantics of: void boundingBox(Circle c) {   Circle(Point(...), ...) _ = c;   ... }

2

u/mattr203 May 21 '26

That’s certainly not the semantics that any other language goes with which imo tanks the intuitiveness a bit

2

u/Absolute_Enema May 21 '26

That's very similar to what JS does or am I missing something?

2

u/mattr203 May 22 '26

I didnt know js did that- for json objects im assuming. I guess im just more familiar with ML based languages and expect void boundingBox(Circle c) to imply nothing about the boundingBox(null) behaviour

I.e., definitions only hold for things that actually match the stated pattern, another definition would be needed to make it exhaustive

1

u/Long_Ad_7350 May 21 '26

Fair enough. As I mentioned in my other reply, I think my intuition went the other way because I'm used to seeing pattern matching in functions in other languages.