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

Unexpected compile-time error when combining generic function and function ref

    XMLWordPrintable

    Details

    • Subcomponent:
    • CPU:
      generic
    • OS:
      generic

      Description

      A DESCRIPTION OF THE PROBLEM :
      The Javac compiler is unable to compile the attached program producing the attached error message. The problem is that for some reason, javac cannot infer the type of type variable T. However, this type can be inferred by the function reference `Foo::m`, and its type should be String.

      Notably, in the following two programs, javac successfully infers T.

      ```
      class Foo {
          public static String m(String x) {
              return x;
          }
      }

      class Test {
          <T> void foo(String x, Function<T, String> y) {}

          void test() {
              foo("F", Foo::m);
          }
      }
      ```

      ```
      class Foo {
          public static <Y> String m(String x) {
              return x;
          }
      }

      class Test {
          void foo(String x, Function<String, String> y) {}

          void test() {
              foo("F", Foo::m);
          }
      }
      ```

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      javac Test.java

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Compile successfully
      ACTUAL -
      Test.java:13: error: incompatible types: cannot infer type-variable(s) T
              foo("F", Foo::m);
                 ^
          (argument mismatch; invalid method reference
            incompatible types: Object cannot be converted to String)
        where T is a type-variable:
          T extends Object declared in method <T>foo(String,Function<T,String>)
      1 error

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

      class Foo {
          public static <Y> String m(String x) {
              return x;
          }
      }

      class Test {
          <T> void foo(String x, Function<T, String> y) {}

          void test() {
              foo("F", Foo::m);
          }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: