(credits: example from OCP Java 17 certification guide by Boyarsky and Selikoff)
To learn lambdas better, I put a breakpoint in the code (IntelliJ IDE) and started stepping through it.
Function<Integer, Integer> before = x -> x + 1;
Function<Integer, Integer> after = x -> x * 2;
Function<Integer, Integer> combinedf = after.compose(before);
System.out.println(combinedf.apply(3));
I was surprised to find that the value for x
has already been assigned.
When I step to the next line, it is again evaluated before the call to combinedf.apply()
I don't understand why.
I thought it might be due to compiler optimization and tried to fool it by not hardcoding the '3'.
Scanner scanner = new Scanner(System.in);
Function<Integer, Integer> before = x -> x + 1;
Function<Integer, Integer> after = x -> x * 2;
Function<Integer, Integer> combinedf = after.compose(before);
System.out.println(combinedf.apply(scanner.nextInt()));
But I get the same result.
I followed @wuhoyt's suggestion and set breakpoint to All. I also split out the code. Now it shows as expected. I do not understand why the breakpoint must be set to All for it to work as expected.
Scanner scanner = new Scanner(System.in);
Function<Integer, Integer> before = x -> x + 1;
Function<Integer, Integer> after = x -> x * 2;
Function<Integer, Integer> combinedf = after.compose(before);
Integer intput = scanner.nextInt();
Integer result = combinedf.apply(intput);
System.out.println(result);