logo

JEP Draft: Enhanced Local Variable Declarations

Posted by mfiguiere |3 hours ago |2 comments

Someone 3 hours ago

FTA:

  void boundingBox(Circle c) {
      if (c instanceof Circle(Point(int x, int y), double radius)) {
That looks weird. An if whose condition always is right looks superfluous. It also makes it look as if one could write things such as

    if (c instanceof Circle(Point(int x, int y), double 1.0)) {
        …
    } else {
        …
    }
Finally, that code is wordy. I know that is the Java way, but couldn’t it be slightly shorter by not requiring specifying basic types as in

      if (c instanceof Circle(Point(x, y), radius)) {
? (I wouldn’t go as far as

      if (c instanceof Circle((x, y), radius)) {
. That doesnt feel Java to me)

mfiguiere 3 hours ago

TLDR

* Destructuring via Record Patterns

The most prominent feature is the ability to use a record pattern on the left-hand side of a local variable declaration. This allows you to "destructure" an object and initialize multiple variables in a single statement.

Traditional way:

  Point p = getPoint();
  int x = p.x();
  int y = p.y();
Enhanced way:

  Point(int x, int y) = getPoint();
This also supports nested patterns, allowing you to reach deep into an object hierarchy in one go:

  Circle(Point(int x, int y), double radius) = getCircle();
* Pattern Matching in Enhanced for Loops

You can now use these same record patterns in the header of an enhanced for loop to extract data from every element in a collection or array.

  for (Circle(Point(int x, int y), double radius) : circles) {
      // Directly use x, y, and radius here
  }