0

I am not quite able to understand why the line1 and line2 in the following code compiles just fine? Can forEach method in Java Stream take a Function functional interface as argument?

On line 1, shouldn't the IntConsumer functional interface that forEach takes have a void return whereas the value1.incrementAndGet() does return a long?

Similarly, wouldn't ++value2[0] return a long and make the code not compile?

public class ShouldItCompile {
    public static void main(String[] args) {
        AtomicLong value1 = new AtomicLong(0);
        final long[] value2 = {0};
        IntStream.iterate(1, i -> 1).limit(100).parallel().forEach(i -> value1.incrementAndGet());//line1
        IntStream.iterate(1, i -> 1).limit(100).parallel().forEach(i -> ++value2[0]);//line2
        System.out.println(value1+" "+value2[0]);
    }
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
skip
  • 12,193
  • 32
  • 113
  • 153
  • 2
    "Any sufficiently advanced type inference rules are indistinguishable from magic" - not Arthur C Clarke. – Dawood ibn Kareem Sep 23 '18 at 21:32
  • [Why is it possible initialize java.util.function.Consumer with lambda that returns value?](https://stackoverflow.com/questions/46103851/why-is-it-possible-initialize-java-util-function-consumer-with-lambda-that-retur?noredirect=1&lq=1) – Sotirios Delimanolis Sep 23 '18 at 21:34
  • [Method Reference - passing Function to method with Consumer argument](https://stackoverflow.com/questions/50377771/method-reference-passing-function-to-method-with-consumer-argument) – Sotirios Delimanolis Sep 23 '18 at 21:35

0 Answers0