Creating an Option

An Option can be created in a variety of ways. The most straightforward, though not recommended, is to use the constructor of the case class or to return None directly:

val opt1 = None
val opt2 = Some("Option")

This is not recommended because it is absolutely possible to return null wrapped in Option again, thus defeating the purpose of it: 

val opt3 = Some(null)

Because of this, we need to check whether the constructor argument is null first:

def opt4[A](a: A): Option[A] = if (a == null) None else Some(a)

In fact, this pattern is so common that the Option companion object provides the corresponding constructor:

def opt5[A](a: A): Option[A] = Option(a)

The companion object defines a few more constructors which allow you to refrain from direct use of Some or None altogether:

val empty = Option.empty[String]
val temperature: Int = 26
def readExactTemperature: Int = 26.3425 // slow and expensive method call
val temp1 = Option.when(temperature > 45)(readExactTemperature)
val temp2 = Option.unless(temperature < 45)(readExactTemperature)

The first constructor creates the type None, and the second and third return Some, but only if the condition is true or false, respectively. The second argument is a by-name parameter and is only calculated if the condition holds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.70.185