oobjhq
Last Updated: February 25, 2016
·
2.028K
· eugener
1de60d98bb69f4a0e2bbad6cd4726e9f

Scala Option Cheatsheet

// flatMap
// This code is equivalent to:
// option.flatMap(foo(_))
option match {
  case None => None
  case Some(x) => foo(x)
}

// flatten
// This code is equivalent to:
// option.flatten
option match {
  case None => None
  case Some(x) => x
}

// map
// This code is equivalent to:
// option.map(foo(_))
option match {
  case None => None
  case Some(x) => Some(foo(x))
}

// foreach
// This code is equivalent to:
// option.foreach(foo(_))
option match {
  case None => {}
  case Some(x) => foo(x)
}

// isDefined
// This code is equivalent to:
// option.isDefined
option match {
  case None => false
  case Some(_) => true
}

// isEmpty
// This code is equivalent to:
// option.isEmpty
option match {
  case None => true
  case Some(_) => false
}


// forall
// This code is equivalent to:
// option.forall(foo(_))
option match {
  case None => true
  case Some(x) => foo(x)
}

// exists
// This code is equivalent to:
// option.exists(foo(_))
option match {
  case None => false
  case Some(x) => foo(x)
}

// orElse
// This code is equivalent to:
// option.OrElse(foo)
option match {
  case None => foo
  case Some(x) => Some(x)
}

// getOrElse
// This code is equivalent to:
// option.getOrElse(foo)
option match {
  case None => foo
  case Some(x) => x
}

// toList
// This code is equivalent to:
// option.toList
option match {
  case None => Nil
  case Some(x) => x :: Nil
}
Say Thanks
Respond
Awesome Job

Bc0a6794 05ee 11e8 902a 778405599bdb
Software Engineer
·
Denver, San Francisco
·
Full Time