Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8366511

Export lambda arrow definition expression syntax to regular method definition

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • tools
    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      Related to: JDK-8161115

      C# can define method with a single statement/expression by `=>` like lambda without using braces:

      ```cs
      record Point(double X, double Y)
      {
          public double Norm() => Math.Sqrt(X * X + Y * Y);
          public override string ToString() => "(" + X + ", " + Y + ")";
      }
      ```

      (Note: C# uses `=>` instead of `->` unlike Java)

      Current:

      ```java
      record Point(double x, double y) {
          public double norm() {
              return Math.sqrt(x * x + y * y);
          }
          public String toString() {
              return "(" + x + ", " + y + ")";
          }
      }
      ```

      Suggestion:

      ```java
      record Point(double x, double y) {
          public double norm() -> Math.sqrt(x * x + y * y);
          public String toString() -> "(" + x + ", " + y + ")";
      }
      ```

      You sometimes have to write tiny methods with a single expression/statement many times; e.g.:

      ```java
      class WhyDontYouUseLombok {
          private int val1;
          private int val2;
          // ...
          public int getVal1() -> val1;
          public void setVal1(int val1) -> this.val1 = val1;
          public int getVal2() -> val2;
          public void setVal2(int val2) -> this.val2 = val2;
          // ...
          public String toString() -> "Please let us use Lombok! Why have you rejected it in our project?";
      }
      ```

      The lambda expression has already been able to be defined by such a syntax:

      ```java
      Stream.generate(() -> r.nextInt(4) == 0 ? "Win" : "Lose").limit(10).forEach(IO::println);
      ```

      Normal methods in classes should also be able to be defined by the same/similar syntax (C# has already been able to do so as "Expression-bodied (function) members").


            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: