Scala Option and Some
The absence of a value during rurtime should be somehow handled otherwise the will be a runtime error. The absent value is a null
value. If we have a value of type D
that may be absent (for example in method, function, class constructor), Scala uses an instance (object) of the (abstract) classOption[D]
as its container. The class Option
has two sub classes Some
and None
. Therefore, an instance of Option
is an instance of either Some
or None
. For a variable x
of type Option[D]
, the factory (of Option[D]
) creates Some(x)
if x != null
or None
if x == null
.
The following are examples of situations to use Option
:
1- Creating a type-Option val:
val optionalIntValue: Option[Int] = Some(1) val optionalValue = Some("abc") // Scala infers the type // or // val optionalIntValue: Option[Int] = None // type is needed
2- When a function may or may not return a value; we want to give it the option to return a value or not:
def myFunc: Option[String] = { ... }
3- When a parameter of a function can be present or absent, i.e being optional to be given:
def myFunc(param1: Option[D]): ... case class MyClass(param1: Option[D], param2: String)
Keeping in mind that Option
is just a type as a container for a value that can be absent, there are several ways to use an Option
-type variable. Examples:
1- The most general way is to use an Option
with a match
. We can define the output of a method as an Option
and handle the output. For example, a function that reads user input. User may just press Enter/Cancel and input nothing.
def readUserInput(): Option[processedUserInputType] = { ... } readUserInput() match { case Some(outputOftheFunction) => // Do something with outputOftheFunction case None => // Do something when there is no output }
This example is to show how to make a parameter of a function optional for the user. If not provided, it will be considered as a predefined value None
.
def show(x: Option[String], y: Option[Int] = None) = { x match { case Some(s) => println(s) case None => println ("?") } y match { case Some(number) => println( s"the number is ${number}") case None => println("no number") } } val myInput1 = Some("hello bear") show(myInput1) // hello bear no number show(None) // ? no number show(None, y=Some(123)) // ? the number is 123
2- Extracting the value of an Option
using getOrElse
method. A default value for the None
case is mandatory.
val someValue1 = Some(123) val someValue2 : Option[Int] = None someValue1.getOrElse(100) // 123 someValue2.getOrElse(100) // 100