Bad interaction between wildcard and functional interface conversion

Remi Forax forax at univ-mlv.fr
Wed May 27 15:29:13 UTC 2015


Hi all,

The way the conversion between a lambda (or a method reference) and a 
functional interface is specified doesn't take wildcard (exactly ? 
super) into account making the concept of contravariance of functional 
interface less intuitive that it should be.

The following code compiles:
   private static void create(Consumer<Consumer<String>> consumer) {
     consumer.accept(s -> System.out.println(s));
   }

This one doesn't compile because "? super Consumer<? super String>" is 
not a functional interface:
   private static void create2(Consumer<? super Consumer<? super 
String>> consumer) {
     consumer.accept(s -> System.out.println(s));
   }

The workaround is to introduce a cast :(
   private static void create3(Consumer<? super Consumer<? super 
String>> consumer) {
     consumer.accept((Consumer<String>)s -> System.out.println(s));
   }
which is stupid in this case because there is no ambiguity.
This cast is just here because the JLS doesn't consider that ? super 
Consumer<...> is a valid target type

IMO, this bug is very similar to JDK-6964923 and i think the spec should 
be changed to allow ? super Foo to be a valid target type for a lambda 
conversion (obviously if Foo is a functional interface).

regards,
Rémi




More information about the core-libs-dev mailing list