Concise way of composing Java method references?

Home / java / Concise way of composing Java method references?

Given some Java 8 method functions:class Foo { Bar getBar() {} }
class Bar { Baz getBaz() {} }
A composition of the two accessors looks like:Function getBarFromFoo = Foo::getBar;
Function getBazFromBar = Bar::getBaz;
Function getBazFromFoo = getBarFromFoo.andThen(getBazFromBar);
Is there a more concise way? This seems to work
((Function) Foo::getBar).andThen(Bar::getBaz)
But it’s rather ugly. The outer parens make sense for precedence reasons, but why is the cast necessary?

(Foo::getBar::getBaz would be nice, but alas…)

Let’s define a functional interface:@FunctionalInterface
interface MyFunctionalInterface {
Bar getBar(Foo f);
We can simplify the method reference Foo::getBar a bit,
(Foo foo) -> foo.getBar();
which means "take a Foo and return a Bar". For that description, a lot of methods are suitable (for instance, our interface with the getBar and a Funtion with its apply):MyFunctionalInterface f1 = (Foo foo) -> foo.getBar();
Function f2 = (Foo foo) -> foo.getBar();
That is the answer to the question why the cast is necessary.

To answer the question whether there is a more concise way affirmatively, we have to set a context. The context unambiguously gives us a Function to continue working with:class Functions {
public static Function of(Function function) {
return function;

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *