Skip to content

Instantly share code, notes, and snippets.

@devnulled
Created June 27, 2012 15:45
Show Gist options
  • Save devnulled/3004942 to your computer and use it in GitHub Desktop.
Save devnulled/3004942 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