I have the following code which compiles successfully:
import java.lang.String;
import java.util.List;
import java.util.Arrays;
interface Supplier<R> {
Foo<R> get();
}
interface Foo<R> {
public R getBar();
public void init();
}
public class Main {
static private <V> void doSomething(final Supplier<? extends List<? extends V>> supplier) {
// do something
}
static public void main(String[] args) {
doSomething(new Supplier<List<Object>>(){
@Override
public Foo<List<Object>> get() {
return new Foo<List<Object>>(){
@Override
public List<Object> getBar() {
return null;
}
@Override
public void init() {
// initialisation
}
};
}
});
}
}
However, if I convert the Supplier
to the following lambda expression the code does not compile anymore:
doSomething(() -> new Foo<List<Object>>(){
@Override
public List<Object> getBar() {
return null;
}
});
The compiler error is:
Main.java:22: error: method doSomething in class Main cannot be applied to given types;
doSomething(() -> new Foo<List<Object>>(){
^
required: Supplier<? extends List<? extends V>>
found: ()->new Fo[...]; } }
reason: cannot infer type-variable(s) V
(argument mismatch; bad return type in lambda expression
<anonymous Foo<List<Object>>> cannot be converted to Foo<List<? extends V>>)
where V is a type-variable:
V extends Object declared in method <V>doSomething(Supplier<? extends List<? extends V>>)
If I change the declaration of the supplier to Supplier<? extends List<V>>
, both variants compile successfully.
I compile the code with a Java 8 compiler.
Why does the code with the lambda not compile, although it is equivalent to the non-lambda version? Is this a known/intended limitation of Java or is it a bug?