In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?
Lambda expressions are possible using java
I like to think of monads in slighlty more mathematical (but still informal) fashion. After that I will explain the relationship to one of Java 8's monads CompletableFuture.
First of all, a monad M is a functor. That is, it transforms a type into another type: If X is a type (e.g. String) then we have another type M (e.g. List). Moreover, if we have a transformation/function X -> Y of types, we should get a function M.
But there is more data to such a monad. We have a so-called unit which is a function X -> M for each type X. In other words, each object of X can be wrapped in a natural way into the monad.
The most characteristic data of a monad, however, is it's product: a function M for each type X.
All of these data should satisfy some axioms like functoriality, associativity, unit laws, but I won't go into detail here and it also doesn't matter for practical usage.
We can now deduce another operation for monads, which is often used as an equivalent definition for monads, the binding operation: A value/object in M can be bound with a function X -> M to yield another value in M. How do we achieve this? Well, first we apply functoriality to the function to obtain a function M. Next we apply the monadic product to the target to obtain a function M. Now we can plug in the value of M to obtain a value in M as desired. This binding operation is used to chain several monadic operations together.
Now lets come to the CompletableFuture example, i.e. CompletableFuture = M. Think of an object of CompletableFuture as some computation that's performed asynchronously and which yields an object of MyData as a result some time in the future. What are the monadic operations here?
thenApply: first the computation is performed and as soon as the result is available, the function which is given to thenApply is applied to transform the result into another typecompletedFuture: as the documentation tells, the resulting computation is already finished and yields the given value at onceCompletableFuture> that computation asynchronously yields another computation in CompletableFuture which in turn yields some value in MyData later on, so performing both computations on after the other yields one computation in totalthenComposeAs you see, computations can now be wrapped up in a special context, namely asynchronicity. The general monadic structures enable us to chain such computations in the given context. CompletableFuture is for example used in the Lagom framework to easily construct highly asynchronous request handlers which are transparently backed up by efficient thread pools (instead of handling each request by a dedicated thread).