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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s