Home » Scala language

Options in Scala

Scala options: Option contains two values none and some other value. In Scala, options are used when a function may or may not return a value. In this Scala tutorial on options, we will learn how to initialize, and perform functions on options with working examples.
Submitted by Shivang Yadav, on July 20, 2019

Scala options

The option is a container that contains one single value which can be one of the two distinct values.

One of the two values is 'none' and others can be any object valid in the program.

The option can be used when accepting values return from a function that can return null the time of period and some value otherwise. the options class returns two Instances:

  1. An instance of a null class, when the function fails.
  2. An instance of some class, when the function and successfully.

Both these classes inherit from the option class.


Declaration of a function that uses option as a return type:

    def function_name(arguments) : Option[data_type]

Example to show how the working of option

object Demo {
   def details(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   def main(args: Array[String]) {
      val student = Map("name" -> "Ram", "standard" -> "10")
      println("show(student.get( \"name\")) : " + details(student.get( "name")) )
      println("show(student.get( \"percentage\")) : " + details(student.get( "percentage")) )


show(student.get( "name")) : Ram
show(student.get( "percentage")) : ?

Option Vs NULL: which is better?

The option is compared to NULL in Java programming. Using null in java, for an occasional outcome need it to be handled. If not handled it may give a NullPointerException. While using the Option in scala this exception does not occur that's why its usage is a bit more effective.

Some common methods of Scala Options class

Method Description
def get : A Returns the value of the option.
def isempty : Boolean Returns true for none value and false otherwise.
def getOrElse(val) Returns value for some value in option and return the passed value if none.
def foreach() Evaluates a function if a value exists otherwise nothing is to be done
def flatmap() Returns the value of function for some value of option. If the value does not exists then returns None.
def productElementName(n) Return the element at the n place in 0 based-index.

Top MCQs

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.