Default andThen() method in BiFunction interface

mark42inbound :

There's a default method andThen() in the BiFunction interface (java.util.function package).

default <V> BiFunction<T,U,V> andThen(Function<? super R,? extends V> after)

The documentation says:

Returns a composed function that first applies this function to its input, and then applies the after function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.

It's little confusing to understand what the explanation means. As per my understanding, a composed function is returned when the default andThen() method is invoked. This composed function is invoked on the types T and U that returns the type V. Finally, there's and after function that is invoked on the types R and V.

What's the need of this method? How does it actually fit in the picture?

Ousmane D. :

It's little confusing to understand what the explanation means.

To explain it as simple as I can, the method andThen returns a function that first applies a given function to an input and then applies another function to the result of that application.

Assume we had two functions f and g , function f doing some logic and function g doing some other type of logic so when you compose f.andThen(g) that essentially means g(f(x)) i.e. we first apply the function given as argument f(x) and then apply the function g to the result.

Example:

BiFunction<Integer, Integer, Integer> f = Math::addExact; 
Function<Integer, Integer> g = e -> e * 2; 
System.out.println(f.andThen(g).apply(10,10)); // 40

We first call function f(10, 10) and then take the result of that which is 20, pass it to the function g(20) and that is executed multiplying 20 by 2 hence yielding 40.

To be honest the syntax to call a function in Java is not the best it can be so I can understand when someone looks at this the first time it might be difficult to grasp and gets harder to follow the more you compose functions, for example in C# one could simply do g(f(10, 10)) which visibly to the eye is easier to follow, read and understand.

What's the need of this method? How does it actually fit in the picture?

In my experience, it's not common that I've composed functions as shown above but a typical scenario I could imagine is if you have various utility methods that do some logic where the result of one function is further passed to other functions for processing in which case you can then use function composition to create various transformation pipelines by composing the utility methods.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466879&siteId=1