Monads are a category of data types. Informally, anything that has a type parameter, a constructor that takes an element of that type, and a flatMap method (which has to obey certain laws) is a monad.
There are many different approaches to explaining monads. One reason for that may be, that different monads have very different effects. You have probably used some monads already: Option
, List
, and Either
are monads. Future
is a monad (if you don’t look too closely). If you look at their APIs, you will notice, that they have similar methods, although they do different things.
The book Scala with Cats explains monads as
A monad is a mechanism for sequencing computations.
which is what methods like map
and flatMap
do. For example, with an Option
, you can use them to chain several functions together, which do not need to handle an absent value. With a List
, you chain operations together, that work on single elements.
A type that has a map
method is called a Functor
, it chains together functions that work on elements of the generic type of the Functor
. A Monad
, which has a flatMap
, is more powerful, as flatMap allows for functions, that return an instance of the Monad, thereby changing the effect the monad has. For example, map
on Option
can only convert a present value to another present value, flatMap
can also convert it to None
. For lists, flatMap
allows to change the length of the list (by returning a different number of elements from the function given to it).
I recommend reading the Scala with Cats chapter on monads, it is free to read online and I think it is well written.