Florian Jedamzik wrote:What is going on here is:
in the Function "func2" the Method that acts up First, is compose(),
after it comes "andThen(). And last but not least func gets to
run, am I right here?
This is what happens:
In the following line:
1. The method 'andThen' is called on 'func' with a lambda expression as its argument. This returns a value, which is another Function object.
2. The method 'compose' is called on the Function that was returned in step 1. This returns another Function object.
When you then call
func2.apply("4") then the following happens:
3. You are calling 'apply' on the Function object that was returned by the 'compose' method in step 2. This method first executes the lambda expression that was passed to it, which is in this case:
(String s) -> Integer.parseInt(s) - so the "4" that you pass to apply() is converted to an int.
4. The 'compose' method then calls 'apply' on the Function object that it was called on in step 2 - so it calls 'apply' with the output of the lambda (the integer 4) on the Function object that was returned in step 1, which was created by the 'andThen' method.
5. The Function object returned by the 'andThen' method does this: it first calls the 'apply' of the Function object on which it was called itself, and then it calls the lambda expression that you passed to it on the result of the first 'apply' (so, this is exactly the opposite order as what 'compose' does). So: func.apply() is called with the integer 4. This translates the integer 4 back into a string "4". And then the lambda
(String s) -> s+"2" is called, which concatenates strings "4" and "2", returning "42".