4

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

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've noticed a lot of questions along the lines "How do I do this thing with these concepts", and the real answer is "you can do it this way, but you shouldn't. Do it the 'classic' way."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.