Image for post
Image for post

One can argue that composing functions is the most important idea in programming and functional programming in particular. The idea of compositionality is of monumental importance in human thinking. Creating systems by composing smaller systems that are easier to implement and design can be found in all levels of programming. Staring from the Syntax of the language, to Design patterns, architectural patterns, larger System design etc.

In this section we are going to take a brief look at one of the most basic ones; Function composition.

Image for post
Image for post

In mathematics, function composition is the application of one function to the result of another to produce a third function. For instance, the functions f : T→ R and g : R→ U can be composed to yield a function h: g(f(x)) which maps T→ U we usually represent that as g ○ f and we read that as “g after f ” the symbol usually represents “after”.

Programmatically for the functional interfaces there are two ways called .andThen() and .compose() to make this composition. If you have a Function<T, R> you can:

Now we are now going to take a brief look at the most common java util Functional interface

Function<,> composition

Since the most usual functional interface is Function<T, R> it provides a default method .andThen (docs.oracle) that takes another Function<R, U> and returns a Function<T, U>

run this : Fiddle

Image for post
Image for post

we can write the composition in the opposite direction using the compose method

Image for post
Image for post

BiFunction<> Composition

BiFunction<U, V, R> also provides an andThen method

Image for post
Image for post

Take a look at the following function composition :

Run This: Fiddle

Supplier<> Composition

The Consumer and Supplier do not provide any composition methods build in, but is easy to imagine even visually a supplier post-compose method :

Image for post
Image for post

We can create an extension for that :

Which we can use like this :

SupplierFunctor<Integer> d = () -> 5;SupplierFunctor<Integer> f = d.andThen(x -> x + 5);

Run This: Fiddle

All the .andThen methods for Functional interfaces are the same as our good old familiar Stream.map(). With a lot of imagination, you can think of ()->5 as a Stream or Array with a single element.

Image for post
Image for post

Excerpt from the book:

Image for post
Image for post
https://leanpub.com/functional-java-with-vavr

Written by

More than 14 years’ experience as full stack developer and Software Architect .https://leanpub.com/u/dimitrispapadim

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store