1

I was comparing the use of compose() default method with its equivalent lambda expression and couldn't find any reason why prefering the former.

Maybe the reason is related to code expressiveness or functional style programming, as pointed here

However, comparing the two approaches to solve the question How to do function composition? I see only disadvantages in using compose() instead of lambda expressions.

1st approach with compose() according to the accepted answer:

Function<Person, Address> personToAddress = Person::getAddress;
Function<Address, String> addressToCountry = Address::getCountry;
Function<Person, String> toCountry = addressToCountry.compose(personToAddress);

2nd approach with a lambda expression:

Function<Person, String> toCountry = p -> p.getAddress().getCountry();

Why do I prefer the second one? First, it is less verbose . Second, it does not require the explicit auxiliary variables personToAddress and addressToCountry.

So, is there any reason for using compose() instead of using a lambda explicitly?

3
  • 4
    The second one is appropriate when the two functions have been passed to you. i.e. they already exist. Commented Mar 29, 2017 at 11:49
  • 2
    In your simple example you know both how to get address from a person and how to get country from address. But what if you don't know how to get an address? What if Person has List<Address> and you don't know which one you are requested? Then you can request a mapper from client callsite and compose the answer. Commented Mar 29, 2017 at 12:06
  • 1
    Just to nit-pick, the local variables are not strictly required. You could use a cast to link the method reference to the Function type Commented Mar 29, 2017 at 15:28

1 Answer 1

2

One reason is if you do not create one or even both of the functions in the same piece of code, but get them passed in from somewhere else. Then you can either write a lambda that calls apply() on the given function(s), or use compose(), which would probably be cleaner.

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

Comments

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.