loading...

Monads for Java programmers in simple terms

siy profile image Sergiy Yevtushenko Updated on ・1 min read

The word Monad frequently used while functional programming is mentioned or discussed. There are several explanation of this term, but even simplest of them tend to explain it using category theory or relying on at least basic functional programming background.

Recently I've discovered for myself, that actually all that is not necessary, monad can be explained to Java programmers using only therms and concepts they are definitely familiar with. The explanation does not pretend to be precise or absolutely correct. Its purpose is to provide general understanding.

So, what is monad?

Monad is:

  • container for some value(s)
  • design pattern

I guess that 'container' part is clear. So, let's go to 'design pattern' part.

Monad is a kind of "inversion of control" comparing to immutable POJO. For POJO you call getter to retrieve value and do what you want with this value. POJO has no control over that use. For monad you provide "processing function" and pass it to some monad method. The result of processing is then returned back to caller in some form.

This inversion gives monad complete control on how processing is performed and enables whole lot of possibilities.

For example, it can avoid calling processing if value stored in monad is actually missing (Maybe monad).

Or apply processing only if stored value is of one of particular type (Either monad) and omit processing otherwise, and so on and so forth.

Note also that Monad do not expose stored value(s) directly (nor via getter), in some cases this is just impossible. This makes some implementations, like introduced in Java 8 Optionalnot a completely monadic.

Posted on by:

siy profile

Sergiy Yevtushenko

@siy

Writing code for 30+ years and still enjoy it...

Discussion

pic
Editor guide