How to change the type of a function reference?

Viewed 90

Java8 lets me use a method declaration as implementation of any of my interfaces, as long as it only contains one method.

However once it is defined, the type cannot be changed.

My code:

import java.util.function.IntConsumer;

public class A {

    interface MyConsumer {
        void doSomething(int i);
    }

    public static void main(String[] args) {
        IntConsumer i = A::consume;
        MyConsumer i2 = A::consume;

        IntConsumer i3 = (IntConsumer) i2; // ClassCastException
        MyConsumer i4 = (MyConsumer) i; // ClassCastException

        IntConsumer i5 = i2; // does not compile
        MyConsumer i6 = i; // does not compile

        IntConsumer i7 = i2::doSomething; // workaround, as suggested by @Eran http://stackoverflow.com/a/35846001/476791
        MyConsumer i8 = i::accept;

        Object i9 = A::consume; // does not compile
        Object i10 = (IntConsumer) A::consume; // works
        Object i11 = (MyConsumer) A::consume; // works
        Object i12 = (MyConsumer) (IntConsumer) A::consume; // does not work
    }

    static void consume(int i) {
        System.out.println(i);
    }
}

Note: if you inline some of the variables, then some of the non-working examples suddenly start to work.

My thoughts in detail:

  1. if IntConsumer i = A::consume is valid, then A::consume has to implement IntConsumer
  2. if MyConsumer i2 = A::consume is valid, then A::consume has to implement MyConsumer
  3. if A::consume implements both, IntConsumer and MyConsumer, then casting should be possible

Is there another way to "cast" or "change" the type of the consumer afterwards?

2 Answers
Related