I working with play for Scala (2.1) and I need to convert an Option[Long]
value to Long
.
I know how to do the opposite, I mean:
def toOption[Long](value: Long): Option[Long] = if (value == null) None else Some(value)
But in my case, I have to pass a value of Option[Long]
as a type into a method that takes Long
.
First of all, your implementation of "the opposite" has some serious problems. By putting a type parameter named Long
on the method you're shadowing the Long
type from the standard library. You probably mean the following instead:
def toOption(value: Long): Option[Long] =
if (value == null) None else Some(value)
Even this is kind of nonsensical (since scala.Long
is not a reference type and can never be null
), unless you're referring to java.lang.Long
, which is a recipe for pain and confusion. Finally, even if you were dealing with a reference type (like String
), you'd be better off writing the following, which is exactly equivalent:
def toOption(value: String): Option[String] = Option(value)
This method will return None
if and only if value
is null
.
To address your question, suppose we have the following method:
def foo(x: Long) = x * 2
You shouldn't generally think in terms of passing an Option[Long]
to foo
, but rather of "lifting" foo
into the Option
via map
:
scala> val x: Option[Long] = Some(100L)
x: Option[Long] = Some(100)
scala> x map foo
res14: Option[Long] = Some(200)
The whole point of Option
is to model (at the type level) the possibility of a "null" value in order to avoid a whole class of NullPointerException
-y problems. Using map
on the Option
allows you to perform computations on the value that may be in the Option
while continuing to model the possibility that it's empty.
As another answer notes, it's also possible to use getOrElse
to "bail out" of the Option
, but this usually isn't the idiomatic approach in Scala (except in cases where there really is a reasonable default value).