javac compilation error when passing method reference to method accepting interface.

Tomasz Kowalczewski tomasz.kowalczewski at gmail.com
Mon Nov 3 11:15:30 UTC 2014


Hi,

please excuse my ignorance if this is a known bug, was discussed here or is
plain silly.

I have a curious problem when calling a method with lambda or method
reference as an argument. This happens on several versions of Java 8
including latest (u25). Test case is:

package test;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;

public class CompilationProblem {

    public void shouldCompile() {
        toMap(() -> new LinkedHashMap()); // Compilation error
        toMap(LinkedHashMap::new); // Compilation error
    }

    public <K, V> Map<K, V> toMap(Func0<? extends Map<K, V>> mapFactory) {
        return null;
    }

    interface Func0<R> extends Callable<R> {

        public R call();
    }
}

The errors are:

Error:(10, 17) java: method toMap in class
pl.codewise.voluum.server.db.CompilationProblem cannot be applied to given
types;
  required: pl.codewise.voluum.server.db.CompilationProblem.Func0<? extends
java.util.Map<K,V>>
  found: ()->new Li[...]Map()
  reason: cannot infer type-variable(s) K,V
    (argument mismatch; bad return type in lambda expression
      java.util.LinkedHashMap cannot be converted to ? extends
java.util.Map<K,V>)

Error:(11, 22) java: incompatible types: no instance(s) of type variable(s)
K,V exist so that java.util.LinkedHashMap<K,V> conforms to ? extends
java.util.Map<K,V>

This test case compiles if Func0 does not extend Callable. How does
Callable influence type inference here? What does it change?

-- 
Regards,
Tomasz Kowalczewski
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20141103/36e67f06/attachment.html>


More information about the compiler-dev mailing list