A simple example of using java builder in a Functional Way!
17 Sep 2017
Problem
Assume you have 2 optional parameters: Maybe(firstName), Maybe(lastName)
You want to instantiate (or build an instance of) Name class which is possibly written in Java with these parameters, if they exist (ie; Maybe.Just, or Option.Some).
Ok! Let us try writing it.
Think of multiple classes similar to Name with multiple (a list of) optional parameters. Now, this is our problem definition. A quick solution would be abstracting out the above function (say f) and fold the list of optional parameters (using f), but that is in fact,
discarding the possibility of using a better mechanism provided by Functional Programming paradigm. Below given is one of the solutions. While this may not be the only solution, it is still a cleaner way of solving this problem.
A Solution
State Monad
I have intentionally avoided the use of State.modify function in scalaz, since it is less
expressive at this stage.
If you don’t know State..
You can see some of my code scribblings on State data-type (without scalaz) in the following links.
You may read them in its order. The comments in code may give you some idea on what is state data type.
That will make you feel comfortable with some notes in scalaz tutorial (Google).