Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda causes compile error "incompatible types" in Java 9, compiles in Java 8

The following code compiles with Java 8 but not with Java 9:

public class CompileErrJdk9 {

    @FunctionalInterface public interface Closure<R> {
        R apply();
    }

    @FunctionalInterface public interface VoidClosure {
        void apply();
    }

    static <R> R call(Closure<R> closure) {
        return closure.apply();
    }

    static void call(VoidClosure closure) {
        call(() -> { closure.apply(); return null; });
    }

    static <T> void myMethod(T data) {
        System.out.println(data);
    }

    public static void main(String[] args) {
        call(() -> myMethod("hello")); //compile error in jdk9
    }
}

This is the error:

CompileErrJdk9.java:24: error: incompatible types: inference variable R has incompatible bounds
        call(() -> myMethod("hello")); //compile error in jdk9
            ^
    upper bounds: Object
    lower bounds: void
  where R is a type-variable:
    R extends Object declared in method <R>call(Closure<R>)
1 error

I've narrowed it down to the type parameter <T> of myMethod; if I drop it and use Object for the parameter type the code compiles. Declaring myMethod as static <T> void myMethod() { } fails as well (in 9 only) even though I'm not using the type parameter.

I've checked the Java 9 release notes and searched for an explanation for this behaviour but did not find anything. Am I correct to assume this is a bug in JDK9, or am I missing something?

like image 226
l4mpi Avatar asked Nov 13 '17 09:11

l4mpi


1 Answers

Oracle has accepted this as a bug with ID JDK-8191290:

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8191290

Update: the bug was closed with the comment "Fixed in 10, won't backport".

like image 145
l4mpi Avatar answered Oct 03 '22 18:10

l4mpi