I've only seen examples such as the following for composing functions (or people using lambdas).
Function<A,B> inner = ....;
Function<B,C> outter = ....;
Function<A,C> result = outter.compose(inner);
I would like to compose the following functions using the "compose" feature and not just invoking them directly.
public class J{
public static B inner(final A a){...}
public static C outter(final B b){...}
}
public class K{
public static Function<A,C> result = (J::outter).compose(J::inner);
}
This doesn't compile. I can't seem to be able to use that "compose" member of java.util.function.Function. How do I do it for traditionally declared functions? I would like to avoid the following:
public class K{
public static Function<A,C> result = (a)-> J.outter(J.inner(a));
}
Can it be done?? Thanks in advance
Method references (and lambdas) need context for them to make sense in source code. That context describes the target functional interface, provides details for type inference for generics, etc.
The use of method references in
public static Function<A,C> result = (J::outter).compose(J::inner);
have no context. What should that first J::outter
be? Why?
Apply a cast to give it that context
public static Function<A, C> result = ((Function<B, C>) J::outter).compose(J::inner);
which, in my opinion, is uglier than the lambda solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With