Scala Option – 13 Simple Methods to Call Option in Scala

1. Scala Option – Objective

In this Scala tutorial, we are going to learn about what is Scala Option. Moreover, we will see Scala Option getOrElse() Method, and Scala isEmpty() Method. Along with this we will discuss several Methods to Call on an Option in Scala: def get: A, def isEmpty: Boolean, def productArity: Int, def productElement(n: Int): Any, def exists(p: (A) => Boolean): Boolean, def orNull etc.

So, let’s explore Scala Option.

Scala Option - 13 Simple Methods to Call Option in Scala

Scala Option – 13 Simple Methods to Call Option in Scala

2. Scala Option

A Scala Option holds zero or one element of a type. This means that it is either a Some[T] or a none object. One place we get an Option value is through the get() method for a Map.

Let’s Learn Scala Map with Examples Quickly & Effectively

We have a Map m here:

scala> m
res109: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1, Ruchi -> 2)
scala> m.get("Megha")
res110: Option[Int] = Some(1)
scala> m.get("Fluffy")
res111: Option[Int] = None

Here, it returns Some(1) when it finds the key “Megha” in the Map (where 1 is the value for that key). And when it doesn’t find the key “Fluffy” in there, it returns None, stating that it couldn’t find the key. This is like java.util.HashMap in Java.

We can also implement a pattern match here.

scala> def show(x:Option[Int])=x match{
    | case Some(i)=>i
    | case None=>"?"
    | }
show: (x: Option[Int])Any
scala> show(m.get("Ayushi"))
res113: Any = 0
scala> show(m.get("Fluffy"))
res114: Any = ?

Learn: Scala Closures with Examples | See What is Behind the Magic

3. getOrElse() Method

This is like get(), except it will give us the default when no value exists. Let’s take two values ‘a’ and ‘b’.

scala> val a:Option[Int]=Some(5)
a: Option[Int] = Some(5)
scala> val b:Option[Int]=None
b: Option[Int] = None
And now, the paydirt.
scala> a.getOrElse(1)
res0: Int = 5

This checks if ‘a’ has a value. Since it does, this returns that value, which is 5.

scala> b.getOrElse(7)
res1: Int = 7

Now here, since ‘b’ has no value, this returns the default, which is 7, as we state.

4. Scala isEmpty() Method

If the Scala Option is None, this returns true; otherwise, it returns false.

scala> a.isEmpty
res2: Boolean = false
scala> b.isEmpty
res3: Boolean = true

Learn: Scala Arrays and Multidimensional Arrays in Scala

Scala Quiz

5. Methods to Call on an Option in Scala

These are some of the methods you will commonly use to call Scala Option.

a. def get: A

This will return the Option’s value.

scala> a.get
res5: Int = 5
scala> b.get
java.util.NoSuchElementException: None.get
 at scala.None$.get(Option.scala:349)
 at scala.None$.get(Option.scala:347)
 ... 28 elided

b. def isEmpty: Boolean

If the Scala Option is None, this returns true. Otherwise, it returns true.

scala> a.isEmpty
res7: Boolean = false
scala> b.isEmpty
res8: Boolean = true

c. def productArity: Int

This Scala Option returns the size of the product.

scala> a.productArity
res9: Int = 1
scala> b.productArity
res10: Int = 0

A product A(x_1, …, x_k) has size k
Read Scala String: Creating String, Concatenation, String Length in detail

d. def productElement(n: Int): Any

This returns the n-th element of product, where indexing begins at 0.

scala> a.productElement(0)
res11: Any = 5
scala> a.productElement(1)
java.lang.IndexOutOfBoundsException: 1
 at scala.Some.productElement(Option.scala:333)
 ... 28 elided
scala> b.productElement(0)
java.lang.IndexOutOfBoundsException: 0
 at scala.None$.productElement(Option.scala:347)
 ... 28 elided

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

If the Scala Option has a value, and this value satisfies the predicate, this returns true. Otherwise, this returns false.

scala> a.exists(x=>{x%2!=0})
res14: Boolean = true

f. def filter(p: (A) => Boolean): Option[A]

If the Scala Option’s value satisfies the predicate, this returns that value.

scala> a.filter(x=>{x%2!=0})
res15: Option[Int] = Some(5)

g. def filterNot(p: (A) => Boolean): Option[A]

If the Option’s value does not satisfy the predicate, this returns that value.

scala> a.filterNot(x=>{x%2!=0})
res16: Option[Int] = None
scala> a.filterNot(x=>{x%2==0})
res17: Option[Int] = Some(5)

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

If the Option has a value, this applies the function to that value, and then returns it.

Do you know about Scala Arrays and Multidimensional Arrays

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

It applies the procedure to the Option’s value and returns it. If the Scala Option is None, this does nothing.

j. def getOrElse[B >: A](default: => B): B

If the Option has a value, this returns it; otherwise, returns the default value.

scala> a.getOrElse(7)
res3: Int = 5
scala> b.getOrElse(7)
res4: Int = 7

Learn: Scala Operator

k. def isDefined: Boolean

If the Option is an instance of Some, this returns true; otherwise, false.

scala> a.isDefined
res5: Boolean = true
scala> b.isDefined
res6: Boolean = false

l. def iterator: Iterator[A]

This returns an iterator on the Option.

scala> a.iterator
res8: Iterator[Int] = non-empty iterator
scala> for(i<-a.iterator){println(i)}

5

m. def map[B](f: (A) => B): Option[B]

If the Option has a value, it applies this function to it, and then returns it.

scala> a.map(x=>{x*x})
res10: Option[Int] = Some(25)

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

If the Option has a value, this returns that. Otherwise, this evaluates the alternative and returns it.
Must Read about Scala Iterator in Detail

o. def orNull

If the Option has a value, this returns it. Otherwise, this returns Null.

So, this was all on Scala Option. Hope you like our explanation.

6. Conclusion

Hence, we studied Scala Option. In addition, we discussed Scala Option getOrElse() Method and Scala isEmpty() Method. At last, we saw several Methods to Call on an Option in Scala. Furthermore, if you have any query, feel free to ask in the comment box.

Related Topics- Scala Closures with Examples 

For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.