Gentle introduction to monads in scala

Live coding session

L2L Warszawa 2019

About me

Sławomir Śledź

Sławomir Śledź

Senior Java/Scala Developer

What is a monad?


In functional programming monad is a design pattern which is used to express how states of computations are changing

In category theory monad is an endofunctor (a functor mapping a category to itself), together with two natural transformations

Monad intuition

We can think about monad like about some smart container keeping some value or values.

This container abstracts away from how this value is kept.

We can have a container

  • aware of whether or not the value exists
  • with more then one value
  • for which getting the value would trigger some kind of IO operation
  • with value which eventually could appear in future
  • with value or error
  • with value dependent on some kind of state
  • with value and some logging information
  • etc

flavors of monads

IO Option Either Future Writer Reader Id Try State List

Monad consists of three parts:

  • type constructor M T
  • type converter (unit, pure, return)
    return(x) : T → M T
  • combinator (bind, >>=, flatMap)
    (mx >>= f) : (M T, T → M U) → M U
  • respect monad laws

monad laws

  • Left identity
                    return a >>= f ≡ f a
  • Right identity
                    m >>= return ≡ m
  • Associativity
                    (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)

monad in scala

trait Monad[M[_]] {

  def pure[A](x: A): M[A]

  def flatMap[A, B](xs: M[A])(f: A => M[B]): M[B]


Let's do some coding :-)


Thank you :-)