Option

The Option type is used frequently in Scala programs, and you can compare this with the null value available in Java, which indicates no value. Scala Option [T] is a container for zero or one element for a given type. An Option [T] can be either a Some [T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some (value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

The basic trait for an Option looks like this:

trait Option[T] {
def get: A // Returns the option's value.
def isEmpty: Boolean // Returns true if the option is None, false
otherwise.
def productArity: Int // The size of this product. For a product
A(x_1, ..., x_k), returns k
def productElement(n: Int): Any // The nth element of this product,
0-based
def exists(p: (A) => Boolean): Boolean // Returns true if this option
is nonempty
def filter(p: (A) => Boolean): Option[A] // Returns this Option if it
is nonempty
def filterNot(p: (A) => Boolean): Option[A] // Returns this Option if
it is nonempty or return None.
def flatMap[B](f: (A) => Option[B]): Option[B] // Returns result of
applying f to this Option's
def foreach[U](f: (A) => U): Unit // Apply given procedure f to the
option's value, if it is nonempty.
def getOrElse[B >: A](default: => B): B // Returns the option's value
if the option is nonempty,
def isDefined: Boolean // Returns true if the option is an instance
of Some, false otherwise.
def iterator: Iterator[A] // Returns a singleton iterator returning
Option's value if it is nonempty
def map[B](f: (A) => B): Option[B] // Returns a Some containing
result of applying f to this Option's
def orElse[B >: A](alternative: => Option[B]): Option[B] // Returns
this Option if it is nonempty
def orNull // Returns the option's value if it is nonempty,
or null if it is empty.
}

For example, in the following code, we are trying to map and show some meagacities that are located in some countries such as India, Bangladesh, Japan, and USA:

object ScalaOptions {
def main(args: Array[String]) {
val megacity = Map("Bangladesh" -> "Dhaka", "Japan" -> "Tokyo",
"India" -> "Kolkata", "USA" -> "New York")
println("megacity.get( "Bangladesh" ) : " +
show(megacity.get("Bangladesh")))
println("megacity.get( "India" ) : " +
show(megacity.get("India")))
}
}

Now, to make the preceding code work, we need to have the show() method defined somewhere. Here, we can do it by Scala pattern matching using Option as follows:

def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}

Combining these as follows should print the accurate and desired result that we are expecting:

package com.chapter4.CollectionAPI
object ScalaOptions {
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
def main(args: Array[String]) {
val megacity = Map("Bangladesh" -> "Dhaka", "Japan" -> "Tokyo",
"India" -> "Kolkata", "USA" -> "New York")
println("megacity.get( "Bangladesh" ) : " +
show(megacity.get("Bangladesh")))
println("megacity.get( "India" ) : " +
show(megacity.get("India")))
}
}

You will get the following output:

megacity.get( "Bangladesh" ) : Dhaka
megacity.get( "India" ) : Kolkata

Using the getOrElse() method, it is possible to access a value or a default when no value is present. For example:

// Using getOrElse() method: 
val message: Option[String] = Some("Hello, world!")
val x: Option[Int] = Some(20)
val y: Option[Int] = None
println("message.getOrElse(0): " + message.getOrElse(0))
println("x.getOrElse(0): " + x.getOrElse(0))
println("y.getOrElse(10): " + y.getOrElse(10))

You will get the following output:

message.getOrElse(0): Hello, world!
x.getOrElse(0): 20
y.getOrElse(10): 10

Moreover, using the isEmpty() method, you can check if the option is None or not. For example:

println("message.isEmpty: " + message.isEmpty)
println("x.isEmpty: " + x.isEmpty)
println("y.isEmpty: " + y.isEmpty)

Now, here's the complete program:

package com.chapter4.CollectionAPI
object ScalaOptions {
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
def main(args: Array[String]) {
val megacity = Map("Bangladesh" -> "Dhaka", "Japan" -> "Tokyo",
"India" -> "Kolkata", "USA" -> "New York")
println("megacity.get( "Bangladesh" ) : " +
show(megacity.get("Bangladesh")))
println("megacity.get( "India" ) : " +
show(megacity.get("India")))

// Using getOrElse() method:
val message: Option[String] = Some("Hello, world")
val x: Option[Int] = Some(20)
val y: Option[Int] = None

println("message.getOrElse(0): " + message.getOrElse(0))
println("x.getOrElse(0): " + x.getOrElse(0))
println("y.getOrElse(10): " + y.getOrElse(10))

// Using isEmpty()
println("message.isEmpty: " + message.isEmpty)
println("x.isEmpty: " + x.isEmpty)
println("y.isEmpty: " + y.isEmpty)
}
}

You will get the following output:

megacity.get( "Bangladesh" ) : Dhaka
megacity.get( "India" ) : Kolkata
message.getOrElse(0): Hello, world
x.getOrElse(0): 20
y.getOrElse(10): 10
message.isEmpty: false
x.isEmpty: false
y.isEmpty: true

Let's take a look at other examples on when to use Option. For example, the Map.get() method uses Option in order to tell the user if the element that he tries to access exists or not. For example:

scala> val numbers = Map("two" -> 2, "four" -> 4)
numbers: scala.collection.immutable.Map[String,Int] = Map(two -> 2, four -> 4)
scala> numbers.get("four")
res12: Option[Int] = Some(4)
scala> numbers.get("five")
res13: Option[Int] = None

Now, we will see how to use exists, which is used to check if a predicate holds for a subset of a set of elements in the Traversal collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.4.221