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

Incorrect Lambda overload resolution

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      openjdk 22.0.1 2024-04-16
      OpenJDK Runtime Environment GraalVM CE 22.0.1+8.1 (build 22.0.1+8-jvmci-b01)
      OpenJDK 64-Bit Server VM GraalVM CE 22.0.1+8.1 (build 22.0.1+8-jvmci-b01, mixed mode, sharing)

      A DESCRIPTION OF THE PROBLEM :
      Compiler picks inapplicable `UnaryOperator` overload instead of `Function` one:

      ```
      import java.util.function.Function;
      import java.util.function.Supplier;
      import java.util.function.UnaryOperator;

      public class Main<T> {
          String map(UnaryOperator<T> mapper) {
              return "op";
          }

          <R> String map(Function<T, R> mapper) {
              return "fn";
          }
          
          public static void main(String args[]) {
            new Main<Integer>().map(i -> "");
          }
      }
      ```

      Compiler picks the `UnaryOperator` method and gives error:
      ```
      error: incompatible types: bad return type in lambda expression
            new Main<Integer>().map(i -> "");
                                         ^
          String cannot be converted to Integer
      ```

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compile

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Compiler pick the correct applicable overload and code compiles
      ACTUAL -
      Compilation failure

      ---------- BEGIN SOURCE ----------
      import java.util.function.Function;
      import java.util.function.Supplier;
      import java.util.function.UnaryOperator;

      public class Main<T> {
          String map(UnaryOperator<T> mapper) {
              return "op";
          }

          <R> String map(Function<T, R> mapper) {
              return "fn";
          }
          
          public static void main(String args[]) {
            new Main<Integer>().map(i -> "");
          }
      }
      ---------- END SOURCE ----------

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

              Created:
              Updated:
              Resolved: