2

While checking out some details of Java's method references I wondered how the following piece of code works:

public class MethodRef {
    private static class MyProcessor {
        private int value;

        MyProcessor(int value) {
            this.value = value;
        } 

        void process() {
            System.out.println(value);
        }
    }

    public static void main(String[] args) {
        Stream.of(1,2,3,4)
        .map(MyProcessor::new)
        .forEach(MyProcessor::process);
    }
}

The MyProcessor::new should act as a Function creating MyProcessor instances with its provided one-param constructor.

However, I wonder why MyProcessor::process can be used as a Consumer though its implementation doesn't take any argument.

My take at this:

The .map() returns a Stream of MyProcessor instances. As process is a non-static method, the compiler will convert the .forEach(MyProcessor::process) to something like .forEach(p -> p.process()), which should be a valid Consumer.

dominik
  • 613
  • 2
  • 6
  • 10

0 Answers0