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

Compilation mismatch for equivalent lambda and method reference

XMLWordPrintable

    • Icon: CSR CSR
    • Resolution: Unresolved
    • Icon: P4 P4
    • 26
    • tools
    • None
    • behavioral
    • low
    • some programs that are currently accepted by javac could be rejected when recompiled. In particular programs that include some method reference expressions could be rejected due to this proposed change
    • Language construct
    • Implementation

      Summary

      The javac compiler is not in sync with the JLS. According to the JLS a capture conversion should be applied when deciding if a method reference is compatible with a given function type. The javac compiler is not applying this capture conversion. As a side effect javac is accepting code that should be rejected.

      Problem

      Code like this one:

      import java.util.function.Supplier;
      
      class Test {
          interface X<T> {
              X<T> self();
          }
          static X<?> makeX() {return null;}
          static <R> X<R> create(Supplier<? extends R> supplier) {return null;}  
          static X<X<?>> methodRef() {
              return create(Test::makeX).self();
          }
      }

      should be rejected by javac. As the JLS mandates that in order to prove the compatibility between a method reference expression and a function type, a capture conversion should be applied. As javac is not applying this capture conversion, programs like the one above are being accepted when they should be rejected.

      Solution

      Apply a capture conversion when determining if a method reference is compatible with a given function type, but do this only for JDK 26 onward in order to minimize compatibility issues.

      Specification

      The related section of the specification, see JLS 24 section §15.13.2: Type of a Method Reference, is included below as a reference:

      A method reference expression is congruent with a function type if both of the
      following are true:
      • The function type identifies a single compile-time declaration corresponding to
      the reference.
      • One of the following is true:
      – The result of the function type is void .
      – The result of the function type is R , and the result of applying capture
      conversion (§5.1.10) to the return type of the invocation type (§15.12.2.6) of
      the chosen compile-time declaration is R ' (where R is the target type that may
      be used to infer R '), and neither R nor R ' is void , and R ' is compatible with
      R in an assignment context.

            vromero Vicente Arturo Romero Zaldivar
            vromero Vicente Arturo Romero Zaldivar
            Maurizio Cimadamore
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated: