Casting Java functional interfaces

Viewed 8666

As always I was looking through JDK 8 sources and found very interesting code:

@Override
default void forEachRemaining(Consumer<? super Integer> action) {
    if (action instanceof IntConsumer) {
        forEachRemaining((IntConsumer) action);
    } 
}

The question is: how Consumer<? super Integer> could be an instance of IntConsumer? Because they are in different hierarchy.

I have made similar code snippet to test casting:

public class InterfaceExample {
    public static void main(String[] args) {
        IntConsumer intConsumer = i -> { };
        Consumer<Integer> a = (Consumer<Integer>) intConsumer;

        a.accept(123);
    }
}

But it throws ClassCastException:

Exception in thread "main" 
    java.lang.ClassCastException: 
       com.example.InterfaceExample$$Lambda$1/764977973 
     cannot be cast to 
       java.util.function.Consumer

You can find this code at java.util.Spliterator.OfInt#forEachRemaining(java.util.function.Consumer)

3 Answers
Related