Scala:Option
lastmod 2020-10-23created 2020-08-274 edits
A type that can represent either the presence or the absence of a value.
About
The subtypes of Option that hold a value are
-
Some[T]if a value is present, - and
Noneif there is no value.
Option is a typical monadic collection, along with Scala:Try, Scala:Future, and others.
When to use it?
When you think of Option, there are usually two things to keep in mind.
- It was made to safely replace null.
- It reminds the user once more to be careful, eliminating the chance of a null exception.
- It is for safe use in continuous chains
- It runs safely in situations with successive computations. That is, it guards against problems arising midway. Note that only certain functions provide this protection, as explained in detail in the table below.
Methods
- get
- Gets the value from the Option
- isDefined
- Checks whether it is #Some.
- isEmpty
- Checks whether it is #None.
- getOrElse
- Uses the value if present; otherwise uses the argument passed in.
Using pattern matching
def testOption(o : Option[Int]) = {
val result = o match {
case Some(n) => n
case None => "nothing"
}
}
Some
/** Class `Some[A]` represents existing values of type
* `A`.
*
* @author Martin Odersky
* @since 1.0
*/
@SerialVersionUID(1234815782226070388L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class Some[+A](@deprecatedName('x, "2.12.0") value: A) extends Option[A] {
def isEmpty = false
def get = value
@deprecated("Use .value instead.", "2.12.0") def x: A = value
}
None
/** This case object represents non-existent values.
*
* @author Martin Odersky
* @since 1.0
*/
@SerialVersionUID(5066590221178148012L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}