functional programming - Concise way of composing Java method references? -
given java 8 method functions:
class foo { bar getbar() {} } class bar { baz getbaz() {} }
a composition of 2 accessors looks like:
function<foo, bar> getbarfromfoo = foo::getbar; function<bar, baz> getbazfrombar = bar::getbaz; function<foo, baz> getbazfromfoo = getbarfromfoo.andthen(getbazfrombar);
is there more concise way? seems work
((function<foo, bar>) foo::getbar).andthen(bar::getbaz)
but it's rather ugly. outer parens make sense precedence reasons, why cast necessary?
(foo::getbar::getbaz
nice, alas...)
let's define functional interface:
@functionalinterface interface myfunctionalinterface { bar getbar(foo f); }
we can simplify method reference foo::getbar
bit,
(foo foo) -> foo.getbar();
which means "take foo
, return bar
". description, lot of methods suitable (for instance, our interface getbar
, funtion<foo, bar>
apply
):
myfunctionalinterface f1 = (foo foo) -> foo.getbar(); function<foo, bar> f2 = (foo foo) -> foo.getbar();
that answer question why cast necessary.
to answer question whether there more concise way affirmatively, have set context. context unambiguously gives function
continue working with:
class functions { public static <i, o> function<i, o> of(function<i, o> function) { return function; } } functions.of(foo::getbar).andthen(bar::getbaz);
Comments
Post a Comment