How to add Options in Scala

Options are Monads and we can perform operations in their underlying types in a typesafe way using Scalaz:

  import scalaz._
  import Scalaz._

  val a: Option[BigDecimal] = BigDecimal("0.123").some
  val b: Option[BigDecimal] = BigDecimal("1.234").some
  val c: Option[BigDecimal] = BigDecimal("2.345").some

  println( (a |@| b |@| c) { _ + _ + _ } )

  //yields: Some(3.702)

and if the chain is broken, we don’t have to worry since it’s getting short-circuited:

  import scalaz._
  import Scalaz._

  val a: Option[BigDecimal] = BigDecimal("0.123").some
  val b: Option[BigDecimal] = None
  val c: Option[BigDecimal] = BigDecimal("2.345").some

  println( (a |@| b |@| c) { _ + _ + _ } )

  //yields: None