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

Vicente-Arturo Romero-Zaldivar vicente.romero at oracle.com
Thu Nov 6 17:30:31 UTC 2014


Hi Tomasz,

The bug you are referring to has already been fixed, please see [1]. The 
bits are not in any public release yet but you can build one from the 
development repos:

for 8: http://hg.openjdk.java.net/jdk8u/jdk8u-dev/langtools
for 9: http://hg.openjdk.java.net/jdk9/dev/langtools/

Thanks,
Vicente

[1]

On 11/03/2014 03:15 AM, Tomasz Kowalczewski wrote:
> 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



More information about the compiler-dev mailing list