funKTionale is a functional library for Kotlin that provides several functional patterns and constructs.

A little bit of history

I started to work on the idea behind funKTionale on late 2012, with a first public release (0.1.5) on April 12, 2013 (It was one of the first Kotlin libraries outside JetBrains). The original idea was to make the Kotlin experience closer to Scala (My daily job involves writing Scala code, and lately TypeScript) but it evolved into something with its own identity and flavour

Let’s compose some functions

Function composition is the application of a function’s return to another function to produce a third function. Very simple.

funKTionale provides extension functions to function types, enabling function composition (drink game idea: one shot per “function” in this post).

To use it, you need to add JCenter on your repos:

And then funktionale-composition (8Kb) to your dependencies:

Or if you want all the goodies, GOTY edition, the whole enchilada, you could add funktionale-all (1372Kb):

For our example, a normal and boring invoice price calculation (I’m sure that there are a better ways to calculate invoice prices, just bear with me for the sake of this example).

So, an Item data class and a stub ItemDao

And now, price calculation

So, three map iterations:

And a sum operation at the end.

Now we could move those functions to vals for a cleaner look

It’s still three map iterations

Now, by the power of function composition, we could transform all three functions into one function (Item to price) with just one map iteration

But, What it this andThen operator?

funKTionale provides three function composition operators

Gang of Four: Decorators

Recently Lovis Möller wrote an entry describing some GoF Patterns implementations on Kotlin.

Mario Fusco rightly pointed that a better implementation for decorators should use function composition.

So let’s implement Lovis’ example with function composition

So, just a couple of simple methods

And with function references (::) they could be composed in several ways.

That’s all for now

In next entries, I’ll cover other funKTionale features, see you there. Bye

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!