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
}
Written by Eugene Ryzhikov
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#