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

Cannot call a method with a parameter of a local class declared in a lambda

XMLWordPrintable

    • b09
    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      OpenJDK 17.0.4.1+1, 19+36, 20-ea+17

      A DESCRIPTION OF THE PROBLEM :
      The compiler complains about an invocation of a method that has a parameter whose type is a local class C declared in a lambda by passing it an instance of C returned by a method because "C cannot be converted to C". The lambda also has to be passed to a method: if it is assigned to a variable, the code compiles.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      javac -Xdiags:verbose Bug.java
      Code is below.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      No error.
      ACTUAL -
      Bug.java:11: error: method takeC in class C cannot be applied to given types;
                              C.takeC(C.giveC());
                               ^
        required: C
        found: C
        reason: argument mismatch; C cannot be converted to C

      ---------- BEGIN SOURCE ----------
      class Bug {
      static void run(Runnable r) {}

      static void main() {
      run(() -> {
      class C {
      static void takeC(C c) {}
      static C giveC() {return new C();}
      }

      C.takeC(C.giveC());
      });
      }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      I was able to work around this bug by declaring the local class outside the lambda.
      class Workaround1 {
      static void run(Runnable r) {}

      static void main() {
      class C {
      static void takeC(C c) {}
      static C giveC() {return new C();}
      }

      run(() -> {
      C.takeC(C.giveC());
      });
      }
      }

      Additionally, storing the argument in a variable and passing the variable's value to the method allows the code to compile.
      class Workaround2 {
      static void run(Runnable r) {}

      static void main() {
      run(() -> {
      class C {
      static void takeC(C c) {}
      static C giveC() {return new C();}
      }

      var c = C.giveC();
      C.takeC(c);
      });
      }
      }

      FREQUENCY : always


            vromero Vicente Arturo Romero Zaldivar
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: