EDUCBA

EDUCBA

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

Scala getOrElse

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala getOrElse

Scala getOrElse

Definition of Scala getOrElse

This method is the part of option class in scala. Also, this method exists for both some and none class in scala. What it basically do is it just evaluates the value of the variable and return us the alternative value if the value is empty. This method works on two things success and fail. It will return us the actual value or the default value according to the response we get. This method is used to return an optional value.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below is the syntax for getOrElse methods as per the scala doc. This method will return us the optional value if the value is coming out to be empty otherwise it will give us the evaluates values or the actual value obtained. We will also see one practice example for better understand of syntax:

final defgetOrElse[B >: A](default: => B): B

Example:

val myVar = toInt("200").getOrElse(10)

In the above line of syntax, we are declaring our variable and here we are trying to type case the string into integer and passing one default value to the getOrElse if the value is empty.

How getOrElse Function Works in Scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value. All these classes can be found in the scala. Option package.

Some of the extended class,syper types of option values are as follow see below;

1. Exteded class available in scala for getOrElse method;

  • IterableOnce[A]
  • Product
  • Serializable

2. Linear type available in scala for getOrElse method;

  • AnyRef
  • Any
  • io.Serializable
  • Product
  • Equal

3. Some of the known sub classes available in scala for getOrElse method;

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,543 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)

None
Some

Now we will see one practical example and understand how it internally works;

object Main extends App{
// Your code here!
valx:Option[Int] = Some(100)
println("value for x is :: " + x.getOrElse(0) )
}

In this example, we are creating one Option variable and assigning it a value 100 by using Some class in scala. After this we are using the getOrElse method get the value of the variable. But here we have initialized some value to the variable so the output will be 100 here. If we have not initialized the value the output would be the default value that we have assigned to the getOrElse method. In order to use this method, the variable should be the instance of Option here because we can use this method as the optional value for variable in scala.

Points keep in mind while working with getOrElsemethod :

  • This method is used as an optional value provider in the scala if the input is empty.
  • We can provide any alternative value by using this method.
  • This method first evaluates the value and then return us the actual or we can say the calculated value.
  • While using Option class one thing we have to keep in mind is we have two Object Some and None. Some takes value and None means not defined value.
  • This method follows the success and failure approach which means success if value present fail if not present.

Examples of Scala getOrElse

Following are the examples are given below:

Example #1

In this example we are using the option class in scala to make use of getOrElse method. We have created two Integer variable for this to test.

Code:

object Main extends App{
// Your code here!
// defining the variable using Option
valy:Option[Int] = None
valx:Option[Int] = Some(100)
// using method getOrElse here for result on variable.
val result1 =   x.getOrElse(0)
val result2 =   y.getOrElse(0)
// printing out the output here .
println("value for the variable one is  :::")
println(result1)
println("value for the variable two is  :::")
println(result2)
}

Output:

Scala getOrElse-1.1

Example #2

In this example we are creating the string objects and using getOrElse method with them here.

Code:

object Main extends App{
// Your code here!
// define variable
valy:Option[String] = None
valx:Option[String] = Some("Hello some value here!!")
// call method here
val result1 =   x.getOrElse("No value provided !!")
val result2 =   y.getOrElse("No value provided !!")
// printing the result here
println("value for the variable one is  :::")
println(result1)
println("value for the variable two is  :::")
println(result2)
}

Output:

Scala getOrElse-1.2

Example #3

In this example, we are using more than one variable with getOrElse method n scala. By using some and none both class because we cannot directly call them on the normal variable it is not the function for them.

Code:

object Main extends App{
// Your code here!
// below we are using some class to define the variable
val variable1:Option[Int] = Some(90)
val variable2:Option[Int] = Some(90)
val variable3:Option[Int] = Some(90)
val variable4:Option[Int] = Some(90)
// Using None class
val variable5:Option[Int] = None
val variable6:Option[Int] = None
val variable7:Option[Int] = None
val variable8:Option[Int] = None
// Applying getOrElse method
val result1 = variable1.getOrElse(0)
val result2 = variable2.getOrElse(1)
val result3 = variable3.getOrElse(2)
val result4 = variable4.getOrElse(3)
val result5 = variable5.getOrElse(4)
val result6 = variable6.getOrElse(5)
val result7 = variable7.getOrElse(6)
val result8 = variable8.getOrElse(7)
println("value for the variable one is  :::")
println(result1)
println("value for the variable two is  :::")
println(result2)
println("value for the variable three is  :::")
println(result3)
println("value for the variable four is  :::")
println(result4)
println("value for the variable five is  :::")
println(result5)
println("value for the variable six is  :::")
println(result6)
println("value for the variable seven is  :::")
println(result7)
println("value for the variable eight is  :::")
println(result8)
}

Output:

Scala getOrElse-1.3

Conclusion

So getOrElse method can we used as an optional or a default value if the input provided is empty. We can use this in a scenario where we have to give some default value for the empty input. Also, it is very easy to use, readable and under stable by the developer, and also it is available for both Some and none class of Option in scala.

Recommended Articles

This is a guide to Scala getOrElse. Here we also discuss the definition and how getOrElse function works in scala? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. Spark Functions
  2. Scala Queue
  3. Constructors in Scala 
  4. Scala Collections

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 Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • 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 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
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
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