English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Scala Option (option) type is used to represent an optional value (has a value or no value).
Option[T] is a container for optional values of type T: If the value exists, Option[T] is a Some[T], and if it does not exist, Option[T] is the object None.
Next, let's take a look at a piece of code:
// Although Scala can define variables without types, I still do so for clarity.
// was defined explicitly
val myMap: Map[String, String] = Map("key1" -> "value")
val value1: Option[String] = myMap.get("key1")
val value2: Option[String] = myMap.get("key2")
println(value1) // Some("value1")
println(value2) // None
In the above code, myMap is a hash map where each key is of type String and the value is also of type String, but differently, its get() method returns a category called Option[String].
Scala uses Option[String] to tell you: 'I will try to return a String, but it may not have a String to give you.'
There is no key in myMap2 This data, the get() method returns None.
Option has two subclasses, one is Some, and the other is None. When it returns Some, it means that the function successfully gives you a String, and you can get that String through the get() function. If it returns None, it means that there is no string to give you.
Another example:
object Test {
def main(args: Array[String]) {
val sites = Map40;"w3codebox" -> "www.oldtoolbag.com", "google" -> "www.google.com")
println("sites.get( \"w3codebox\" ) : " + sites.get( "w3codebox" )) // Some(www.oldtoolbag.com)
println("sites.get( \"baidu\" ) : " + sites.get( "baidu" )) // None
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test sites.get( "w3codebox" ) : Some(www.oldtoolbag.com) sites.get( "baidu" ) : None
You can also use pattern matching to output matching values. For example:
object Test {
def main(args: Array[String]) {
val sites = Map40;"w3codebox" -> "www.oldtoolbag.com", "google" -> "www.google.com")
println("show(sites.get( \"w3codebox\")) : " +
show(sites.get( "w3codebox")) )
println("show(sites.get( \"baidu\")) : " +
show(sites.get( "baidu")) )
}
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test show(sites.get( "w3codebox")) : www.oldtoolbag.com show(sites.get( "baidu")) : ?
You can use the getOrElse() method to retrieve an element that exists in the tuple or use its default value, as shown below:
object Test {
def main(args: Array[String]) {
val a:Option[Int] = Some(5)
val b:Option[Int] = None
println("a.getOrElse(0): " + a.getOrElse40;0) )
println("b.getOrElse(10): " + b.getOrElse40;10) )
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test a.getOrElse(0): 5 b.getOrElse(10): 10
You can use the isEmpty() method to detect if the element in the tuple is None, as shown in the following example:
object Test {
def main(args: Array[String]) {
val a:Option[Int] = Some(5)
val b:Option[Int] = None
println("a.isEmpty: " + a.isEmpty )
println("b.isEmpty: " + b.isEmpty )
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test a.isEmpty: false b.isEmpty: true
The following table lists the commonly used methods of Scala Option:
Serial number | Methods and descriptions |
---|---|
1 |
def get: A Get the optional value |
2 |
def isEmpty: Boolean Detects if the optional type value is None, returns true if it is, otherwise returns false |
3 |
def productArity: Int Returns the number of elements, A(x_1, ..., x_k), returns k |
4 |
def productElement(n: Int): Any Get the specified optional starting with 0. That is, A(x_1, ..., x_k), returns x_(n+1) , 0 < n < k. |
5 |
def exists(p: (A) => Boolean): Boolean Returns true if the element specified by the condition exists in the optional and is not None, otherwise returns false. |
6 |
def filter(p: (A) => Boolean): Option[A] If the option contains a value and the condition function passed to filter returns true, filter will return Some example. Otherwise, the return value is None. |
7 |
def filterNot(p: (A) => Boolean): Option[A] If the option contains a value and the condition function passed to filter returns false, filter will return Some example. Otherwise, the return value is None. |
8 |
def flatMap[B](f: (A) => Option[B]): Option[B] If the option contains a value, pass it to the function f for processing and return, otherwise return None. |
9 |
def foreach[U](f: (A) => U): Unit If the option contains a value, pass each value to the function f; otherwise, do not process. |
10 |
def getOrElse[B >: A](default: => B): B If the option contains a value, return the option value; otherwise, return the set default value. |
11 |
def isDefined: Boolean If the optional value is an example of Some, return true; otherwise, return false. |
12 |
def iterator: Iterator[A] If the option contains a value, iterate over the optional values. If the optional value is empty, return an empty iterator. |
13 |
def map[B](f: (A) => B): Option[B] If the option contains a value, return Some processed by the function f; otherwise, return None. |
14 |
def orElse[B >: A](alternative: => Option[B]): Option[B] If an Option is None, the orElse method will return the value of the named parameter, otherwise, it will directly return this Option. |
15 |
def orNull If the option contains a value, return the option value; otherwise, return null. |