Monads in real life

After going through a lot of theory about monads, it would now be useful to go through some code that demonstrates how to implement and use the theoretical concepts, which real-world situations they are good for, and so on.

Let's now do something similar to what we did before, and show what a monad trait will look like in Scala. Before doing this, however, let's slightly change our functor definition:

trait Functor[T] {  def map[Y](f: T => Y): Functor[Y]}

In the preceding code, instead of passing the element that will be mapped, we assume that the type that mixes Functor will have a way to pass it to the map implementation. We also changed the return type so that we can chain multiple functors using map. After we've done ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.