EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala Option

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala Option

Scala Option

Introduction to Scala Option

Scala Option is used in Scala Object oriented programming whenever the return type of function can be a null. It has the values of a type or none in it, so the method returns an instance of option with the values whether be it any values or none. So in Scala Option if that value is returned, it is given back with some class generated and if no values are returned the none class is generated. Some and none called be called as the children of option class.

Syntax and Parameters:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

classOption [+A] extends Product with Serializable

Option has the type parameterized. We can define an option and give the data type whatever we want to for that.

Option[String], Option[Int], Option[File] etc.

The value could be either some or none class.

Scala Option working with Examples

Scala Option checks the return type of the method and returns the value with the some class if there is a value returned or else none is returned for a null value. Whenever a null is returned over a normal function and when it is not handled with in the program we are most liable to get an error of NULLpointerException, but with the help of option over the scala code we will not get this Null pointer Exception. It is better used with Match function.

Let us check the methods and way to create Scala Option with examples:

Example #1

Code:

object Main extends App {
val a = Map("Arpit" -> "Banglaore","Anand" -> "Developer")
val b = a.get("Arpit")
val c = a.get("Aman")
println(b)
println(c)
}

Output:

Scala Option 1

This some and none are part of Scala Option that searches for the key and returns the value if it founds that and none is returned if it doesn’t find the value. So here it uses the Scala Option to fetch the value and handle none.

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,191 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #2

Code:

object Main extends App {
val e = Map(1 ->"A" , 2 -> "b" , 3 -> "c")
val b = e.get(1)
val c = e.get(4)
println(b)
println(c)
}

Output:

Scala Option 2

It can be best use when we have to implement the Scala Pattern Matching.

Let us check how we use that with the help of example:

Example #3

Pattern matching matches the values over the collection what ever it is if the particular thing is found it returns the value else nothing is returned. So we will check how this is achieved with the help of Options.

Code:

object Main extends App {
def matc(a : Option[String]) = a match
{
case Some(v) => ("This the the Returned Value "+v)
case None => ("Nothing Found")
}
val f = Map("Arpit" -> "Bangalore" ,"Anand" -> "Pune")
val b = matc(f.get("Arpit")
)
val c = matc(f.get("Aa"))
println(b)
println(c)
}

Output:

Scala Option 3

We made a function named as matc that takes up the Option as an input and then checks whether the element is found or not, if the element is found we will get the value and if not the nothing return string is returned. A map is made with the key and value. Then this matches the value and we get the String written inside as the result and if nothing is there none is returned.

Methods

Given below are the methods that can be used with Scala Option:

1. isEmpty

It checks whether the result we got from the option is Empty or Not. It returns a Boolean Value.

Example:

Code:

object Main extends App {
def matc(a : Option[String]) = a match
{
case Some(v) => ("This the the Returned Value "+v)
case None =>  ("Nothing Found")
}
val f = Map("Arpit" -> "Bangalore" ,"Anand" -> "Pune")
val res20 = matc(f.get("Arpit")
)
val res19 = matc(f.get("Aa"))
val d = res20.isEmpty
val e = res19.isEmpty
println(res20)
println(res19)
println(d)
println(e)
}

Output:

isEmpty

2. Non Empty

Returns True if it is Non Empty.

Example:

Code:

object Main extends App {
def matc(a : Option[String]) = a match
{
case Some(v) => ("This the the Returned Value "+v)
case None =>  ("Nothing Found")
}
val f = Map("Arpit" -> "Bangalore" ,"Anand" -> "Pune")
val res20 = matc(f.get("Arpit")
)
val res19 = matc(f.get("Aa"))
val d = res20.nonEmpty
val e = res19.nonEmpty
println(res20)
println(res19)
println(d)
println(e)
}

Output:

NON EMPTY

3. Zip And Unzip

Zips the value of the option it gets and makes a paired value, where as unzip helps in unzipping the values from each other.

Example:

Code:

object Main extends App {
def matc(a : Option[String]) = a match
{
case Some(v) => ("This the the Returned Value "+v)
case None =>  ("Nothing Found")
}
val f = Map("Arpit" -> "Bangalore" ,"Anand" -> "Pune")
val res20 = matc(f.get("Arpit")
)
val res19 = matc(f.get("Aa"))
val c = res19 zip res20
val e = c.unzip
println(c)
println(e)
}

Output:

ZIP And UNZIP

4. getOrElse

It is just like an if else method, this works like if the option has some values get that or else return the default value.

Example:

We are creating a variable of type Option with some and none values inside it.

Code:

object Main extends App {
val a : Option[Int] = Some(5)
val b : Option[Int] = None
val c : Option[String] = Some("Arpit")
println(a.getOrElse(10))
println(a.getOrElse(3))
println(b.getOrElse(0))
println(b.getOrElse(3))
println(b.getOrElse(4))
println(c.getOrElse("Annad"))
println(c.getOrElse(4))
println(c.getOrElse(4.0))
}

Output:

Scala Option 7

Here a, b, c are three variables of type Option having the type inside as String and Int.

The get or else method will check if it has some value and return accordingly.

Conclusion

From the above article we saw how Scala Option works and the benefit of using Scala Option over the Object oriented programming. With the help of examples we saw how Scala option handles the null values and the various results associated with it. We checked the syntax and functioning for Scala Option, so Scala Option is a better and a good approach for Scala Object Oriented Programming.

Recommended Articles

This is a guide to Scala Option. Here we discuss the introduction to scala option working along with methods used and respective examples. You may also have a look at the following articles to learn more –

  1. Scala Queue
  2. Scala flatMap
  3. Scala if else
  4. Scala Trait

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training Course Learn More