Simple Introduction to Monads With Java Examples

Monads are heavily used in most functional programming languages. In Haskell, for example, they are essential and appear everywhere, in all kinds of applications and libraries.                            

On the other hand, monads are rarely used in popular, non-pure-functional programming languages like C#, Java, Python, etc.

What Is a Monad? Basic Theory for a Java Developer

As you can guess from the title, the main topic of this article will be monads. I will try to dive deep in their structure and inner workings. With some help of Java Optional, I will try to describe all of this in a more detailed way. At the end of this article, I will implement a log monad — a type of a writer monad —and then describe the role of each major code fragment and provide a simple example of its usage.

Why Learn How Monads Work?

First of all, it is always good to have a basic understanding of how things that we use work. If you are a Java developer, you probably use monads without even knowing about it. It may surprise you, but two of the most commonly known Java 8 features are monad implementations, namely Stream and Optional. In addition, functional programming becomes more and more popular nowadays so it is possible that we will have more similar monadic structures. Then, this knowledge will be even more very valuable.

Let’s start with describing what a monad is – more or less accurately. In my opinion, the matter here is fairly straightforward.