Introduction

In Scalaz library, a wrapper exists for functions of type A => M[B] where M is a Monad called Kleisli. This blog post is an explanation about this wrapper.

Why need Kleisli?

As an example is always a great starting point to convey any concept, I will explain a simple use case where we can use Kleisli. As explained above, Kleisli is a wrapper for functions of type A => M[B] where M is a Monad. Imagine an enterprise application, which serves a REQUEST Url /foo/bar?a=1, and returns back response after talking to 3 Services S1, S2, S3 and performing 2 DB operations D1 and D2 in sequence. So we essentially do 5 IO operations to fulfill this client request. As you know, if a function has a side-effect it makes the function impure and makes it harder to compose. Functional composition is the core of doing functional programming. How do we get around this problem? Well the solution is to “Describe the IO Computation and then finally executing it”. We describe IO operations in an IO Monad[Yes, scalaz has an IO Monad type, by looking at the type, we know that there will be a side-effect], but the key take away is we just describe the IO computations and then combine/compose them and finally execute all of them at one shot using unsafePerformIO method on the IO Monad. Now coming back to the original problem, we are doing 5 IO operations in sequence, how do we compose/combine functions which take some input of type A and return IO[?]? Well, the answer is to use Kleisi as it is a wrapper for functions of type A => M[B]

Code Example

Below code sample shows a simple use case where, “Given employeeId Key we will get Employee details by making a database call”:

DAO

Intermediate Layer accessing DAO

Model

Runner – Main Application