Skip to content

Instantly share code, notes, and snippets.

@eugener
Forked from devnulled/OptionCheatsheet.scala
Created December 3, 2012 03:00
Show Gist options
  • Save eugener/4192328 to your computer and use it in GitHub Desktop.
Save eugener/4192328 to your computer and use it in GitHub Desktop.
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment