Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 How Compose Functions without Lambdas?

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

like image 589
jordan3 Avatar asked Feb 10 '23 08:02

jordan3


1 Answers

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.

like image 104
Sotirios Delimanolis Avatar answered Feb 16 '23 04:02

Sotirios Delimanolis