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

Method reference to instance method with type mismatch causes misleading error

    XMLWordPrintable

Details

    • generic
    • generic

    Description

      A DESCRIPTION OF THE PROBLEM :
      A method reference in the form ReferenceType::identifier to an instance method with mismatching receiver type leads to a misleading error.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Try to compile the code provided below

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      javac errors should say that the required type is `MethodRefTest` but the actual type is `Object`.
      ACTUAL -
      javac errors (erroneously) say there is an argument length mismatch:

      MethodRefTest.java:8: error: incompatible types: invalid method reference
              Consumer<Object> c1 = MethodRefTest::doSomething;
                                    ^
          method doSomething in class MethodRefTest cannot be applied to given types
            required: no arguments
            found: Object
            reason: actual and formal argument lists differ in length
      MethodRefTest.java:9: error: incompatible types: invalid method reference
              BiConsumer<Object, String> c2 = MethodRefTest::consume;
                                              ^
          method consume in class MethodRefTest cannot be applied to given types
            required: String
            found: Object,String
            reason: actual and formal argument lists differ in length
      2 errors

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

      class MethodRefTest {
          void doSomething() { }
          void consume(String s) { }
          
          void test() {
              Consumer<Object> c1 = MethodRefTest::doSomething;
              BiConsumer<Object, String> c2 = MethodRefTest::consume;
          }
      }

      ---------- END SOURCE ----------

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated:
              Resolved: