Scala Option and Iterators Example

Filed Under: Scala

Scala Option can be defined as container that holds zero or more elements of the given type. The option[T] can return Some[T] or None object which represents a missing value.

Consider an example of how to create a option;

val msg : Option[String] = Some("Option is a Scala collection")

Consider an example of how to assign a none value;

val msg : Option[String] = None

Create Student.scala class in Scala IDE as;

case class Student(
  id: Int,
  Name: String,
  marks: Float,
  gender: Option[String])

object TestStudent {
  private val students = Map(1 -> Student(10, "John", 62.5f, Some("male")),
    2 -> Student(12, "Adam", 70.5f, Some("female")))
  def findById(id: Int): Option[Student] = students.get(id)
  def findAll = students.values

Here we are defining a class student with id, name, marks and gender as attributes. Create an object TestStudent in which we define findById method that returns an Option of type Student and findAll which retrieves the values from students map.

Now create another object s1.scala as

object S1 {

  def main(args: Array[String]) {
    val st1 = TestStudent.findById(2)
    if (st1.isDefined) {



Below image shows the output produced when we run S1 as scala application.


Let’s look at some other examples for Scala Option.

Specifying default value

The default value can be specified using getOrElse method.

For example create a scala object as below:

object GetorElse {
  def main(args: Array[String]) {
    val stud = Student(14, "Chris", 45f, None)
    println(stud.gender.getOrElse("Gender not specified"))


Below image shows the output produced as default value since gender was missing.


The gender is specified as None while creating stud instance and hence the message “Gender not specified” is printed.

Pattern Matching

The optional values can be taken apart through pattern matching.

For instance:


object KeyPatternMatch {
  def main(args: Array[String]) {
    val student = Map(12 -> "Anderson", 14 -> "Reena")
    println("Student Name with id 12  : " + displaykey(student.get(12)))
    println("Student Name with id 14 : " + displaykey(student.get(14)))


  def displaykey(a: Option[String]) = a match {
    case Some(t) => t
    case None    => "?"


Student Name with id 12  : Anderson
Student Name with id 14 : Reena

isEmpty() method

The isEmpty() method is used to check whether the option returns empty or not.

For example;

object Empty {
  def main(args: Array[String]) {
    val x: Option[Int] = Some(5)
    val y: Option[Int] = None

    println("Check X is Empty: " + x.isEmpty)
    println("Check Y is Empty: " + y.isEmpty)

It produces below output.

Check X is Empty: false
Check Y is Empty: true

Useful Option Methods

def isDefined: Boolean → Returns true if the option is an instance of Some, else returns false

def or Null → Returns the option’s value if it is nonempty, or null if it is empty.

def isEmpty: Boolean → Returns true if the option is None, false otherwise.

def get: X → Returns the option’s value.

def foreach[Y](f: (Z) => Y): Unit → Apply the given procedure f to the option’s value, if it is nonempty.

Scala Iterators

An Iterator allows user to iterate over the collection thereby accessing all the elements. The core operations of iterator are next and hasNext. The next elements return the successive element and hasNext checks whether the element is present or not.

For example;

Create the scala object Iterator.scala as

object Car {
  def main(args: Array[String]) {
    val car = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")

    while (car.hasNext) {



Length of Iterator

The size or length methods can be used to find the number of the elements in the iterator.

For example,

object CarLength {
  def main(args: Array[String]) {
    val c1 = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")
    val c2 = Iterator("Volkswagen", "Alto", "Xylo", "Innova")
    println("Iterator c1 : " + c1.size)
    println("Length of c2 : " + c2.length)



Iterator c1 : 5
Length of c2 : 4

Finding Minimum and Maximum Elements

The it.min and it.max methods are used to find the minimum and maximum elements in the iterator.

Create scala object MinMax.scala as;

object MinMax {
   def main(args: Array[String]) {
  	val m1 = Iterator(12,45,67,89)
  	val m2 = Iterator(44,66,77,88)
  	println("Smallest element " + m1.min )
  	println("Largest element " + m2.max )



Smallest element 12
Largest element 88

Useful Iterator Methods

def addString(x: StringBuilder): StringBuilder → Returns the string builder x to which elements were appended.

def buffered: BufferedIterator[X] → Creates a buffered iterator from this iterator.

def foreach(f: (X) => Unit): Unit → Applies a function f to all values produced by this iterator.

def indexOf(elem: Y): Int → Returns the index of the first occurrence of the specified object in this iterable object.

def product: X → Multiplies the elements of this collection.

That’s all for Scala Option and Iterators, we will look into Scala Traits in the next tutorial.

Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content