options in scala
DESCRIPTION
A quick tour of Options in Scala.TRANSCRIPT
Options in Scala
A quick tour
Option[Introduction]
An Option represents an optional value through either:
• An instance of Some[Type]• The object None
An option can be typed by:
• Option[Type]
Option[Inheritance]
Option[Null]
Options allow for null checking, but this misses the point and conciseness.
val optionalValue = Some[3]
val value = if (optionalValue.isDefined) optionalValue.get
Options give more than preventing NullPointerExceptions.
Option[PatternMatching]
A more interesting, but still not quite idiomatic approach is pattern matching:
val optionalValue = Some[3]
optionalValue match { case Some(number) => // its a number! case _ => // anything else}
Option[Default]
val optionalValue = Some[3]
val value = optionalValue getOrElse 0
Option[Idiomatic]
Option[+A] can be considered to be a subtype of Traversable with either one or zero elements.
This allows use of collection based functions like map and filter.
Option[Transformations]
val personOpt: Option[Person] = findPerson()
val deptNameOption: Option[String] = personOpt map { _.department } map { _.name }
val deptName = deptNameOption getOrElse ""
Option[ListComprehension]
val personOption: Option[Person] = findPerson()
val deptNameOption = for { person <- personOption department <- person.department name <- department.name if name != "Engineering"} yield name
val deptName = deptNameOption getOrElse ""
List[Question]