Scala Option

Scala 集合Scala Collections

The Scala Option type is used to indicate that a value is optional (has a value or has no value).

Option[T] is a container for an optional value of type T: if the value exists, Option[T] is a Some[T]; if it does not exist, Option[T] is the object None.

Next, let's look at a piece of code:

// Although Scala allows you to omit variable types, for clarity I will
// explicitly define it
 
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 whose Key type is String and Value type is String, but the difference is that its get() returns a type called Option[String].

Scala uses Option[String] to tell you: "I will find a way to return a String, but there may be no String for you."

myMap does not contain the key2 data, so the get() method returns None.

Option has two subcategories, one is Some and the other is None. When it returns Some, it means the function successfully gave you a String, and you can obtain that String through the get() function. If it returns None, it means there is no string for you.

Another example:

Example

object Test {
   def main(args: Array[String]) {
      val sites = Map("example" -> "www.example.com", "google" -> "www.google.com")
     
      println("sites.get( \"example\" ) : " +  sites.get( "example" )) // Some(www.example.com)
      println("sites.get( \"baidu\" ) : " +  sites.get( "baidu" ))  //  None
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
sites.get( "example" ) : Some(www.example.com)
sites.get( "baidu" ) : None

You can also use pattern matching to output the matched value. Example:

Example

object Test {
   def main(args: Array[String]) {
      val sites = Map("example" -> "www.example.com", "google" -> "www.google.com")
     
      println("show(sites.get( \"example\")) : " +  
                                          show(sites.get( "example")) )
      println("show(sites.get( \"baidu\")) : " +  
                                          show(sites.get( "baidu")) )
   }
   
   def show(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
show(sites.get( "example")) : www.example.com
show(sites.get( "baidu")) : ?

getOrElse() Method

You can use the getOrElse() method to obtain an element that exists in the tuple or use its default value. Example:

Example

object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None
     
      println("a.getOrElse(0): " + a.getOrElse(0) )
      println("b.getOrElse(10): " + b.getOrElse(10) )
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
a.getOrElse(0): 5
b.getOrElse(10): 10

isEmpty() Method

You can use the isEmpty() method to check whether the element in the tuple is None. Example:

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 )
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
a.isEmpty: false
b.isEmpty: true

Commonly Used Methods of Scala Option

The following table lists the commonly used methods of Scala Option:

No. Method and Description
1

def get: A

Get the optional value.

2

def isEmpty: Boolean

Check whether the optional value is None; return true if it is, otherwise return false.

3

def productArity: Int

Return the number of elements. For A(x_1, ..., x_k), return k.

4

def productElement(n: Int): Any

Get the specified optional value, starting from 0. That is, for A(x_1, ..., x_k), return x_(n+1), where 0 < n < k.

5

def exists(p: (A) => Boolean): Boolean

If an element in the optional value that satisfies the specified condition exists and is not None, return true; otherwise return 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 returns a Some instance. 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 returns a Some instance. Otherwise, the return value is None.

8

def flatMap[B](f: (A) => Option[B]): Option[B]

If the option contains a value, return the result after passing it to function f; otherwise return None.

9

def foreach[U](f: (A) => U): Unit

If the option contains a value, pass each value to function f; otherwise do nothing.

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

Return true if the optional value is an instance of Some; otherwise return false.

12

def iterator: Iterator[A]

If the option contains a value, iterate over the optional value. 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 a Some processed by function f; otherwise return None.

14

def orElse[B >: A](alternative: => Option[B]): Option[B]

If an Option is None, the orElse method returns the value of the by-name parameter; otherwise, it directly returns this Option.

15

def orNull

Return the option value if the option contains a value; otherwise return null.

Scala 集合Scala Collections

Other Extensions