And as before, this is not going to be about qualities, neither comparison with Java, this is about code, to show how we could solve solutions with it.
All the code posted here is available in this git repo and you could follow the tests incrementally to understand this concepts.
note : I’m not an expert in Kotlin and probably many things that I do here are not how you should code it, this is just for demonstration porpoises.
To simplify the code it will start from where we end in the previous post, with this Java class:
Our functions:
And how we use it:
Java ‘like’ approach
A fist approach with a direct implementation from Java:
Our functions:
And how to use it:
This is very look like to our Java implementation but shorter due some of the benefits from Kotlin, like we only need a pipe function since every
function in Kotlin returns a value Unit (equivalent to void) where there is not output.
However I think we could improve it, so let’s do it so.
Who need a wrapper class?
Let’s do just a pipe function attached to any type:
We don’t need to change our functions, so the example is:
This is nicer, and we get rid of the wrapper class because Kotlin extensions functions, but we could take another approach.
Pipe as an operator!
So let’s change our pipe function to be an operator:
Now this could be use like this:
Interesting but we could even do a step further we a couple of changes
Semantics matters
Let’s create another infix, that actually use the previous one:
And change our functions to be part of a companion object:
So now we could use them like this:
I can understand that this whole operators things is not for everyone, neither to use for everything so we have one
last way to do this that may be better.
Who need pipes? just connect things with normal Kotlin
No pipe functions, change our normal functions into extensions:
So know the example is:
Any of this examples will have the same qualities that we talk about before, small blocks that connect things, that can be unit tested and
they could be use to simplify building complex functionality.
So to answer the main question: “Why we should use functional programming with Kotlin?”
So again, as I said in the previous post:
Not because syntax, not because is trendy, just do it if you could find a useful piece of code that allow you to solve a problem in a way that make sense for you.
About Juan Medina I'm just a normal geek that code all kind of stuff, from complex corporate applications to games.
Games, music, movies and traveling are my escape pods.