The Option monad

We have already mentioned a few times that the standard Scala Option is a monad. In this subsection, we will provide our own monadical implementation of this standard class and show one of the many possible uses of monads.

In order to show how useful the option is, we will see what happens if we don't have it. Let's imagine that we have the following classes:

case class Doer() {  def getAlgorithm(isFail: Boolean) =    if (isFail) {      null    } else {      Algorithm()    }}case class Algorithm() {  def getImplementation(isFail: Boolean, left: Int, right: Int): Implementation =    if (isFail) {      null    } else {      Implementation(left, right)    }}case class Implementation(left: Int, right: Int) {  def compute: Int = left + right}

In order to test, we have ...

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.