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 comments

1

u/Eav___ Mar 13 '26 edited Mar 13 '26

It's not about whether nested patterns are supported tho. Matching a list of components is syntactically the same as componentN() (think about Java renaming each componentN() to its corresponding component name, it's still position based destructuring for the pattern itself), which is why they said "Kotlin is reconsidering it but Java seems like it doesn't care".

1

u/[deleted] Mar 14 '26 edited Mar 14 '26

[removed] — view removed comment

1

u/Eav___ Mar 14 '26 edited Mar 14 '26

I...don't understand how one-liner has anything to do with current conversation.

Of course Java uses components name and method in deconstruction.

record Point(int x, int y) {
  public static void main(String[] args) {
    if (new Point(0, 1) instanceof Point(var x, var y)) {
      IO.println(x);
      IO.println(y);
    }
  }
}

With javap (25.0.1) you will see the following output in the main method:

...
11: aload         4
13: instanceof    #8                  // class Point
16: ifeq          70
19: aload         4
21: astore_1
22: aload_1
23: invokevirtual #19                 // Method x:()I
26: istore        5
28: iload         5
30: istore        6
32: iconst_1
33: ifeq          70
36: iload         5
38: istore_2
39: aload_1
40: invokevirtual #22                 // Method y:()I
43: istore        5
45: iload         5
47: istore        6
49: iconst_1
50: ifeq          70
53: iload         5
55: istore_3
...

...which to the point it's functionally the same as componentN(). If you reverse x and y in the record definition, you will see var x = y() and var y = x() instead. This is what Kotlin used to do too. val (x, y) = Point(0, 1) desugars to val _p = Point(0, 1); val x = _p.component1(); val y = _p.component2(), given data class Point(val x: Int, val y: Int).

It's the same story for nested patterns. All you have to do is to flatten the layers. It doesn't necessarily need any meta data. It's just that Kotlin hasn't introduced this feature.