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". Any help please.
If you have x as Option[Long],
x.get
will give you 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 theLong
type from the standard library. You probably mean the following instead:Even this is kind of nonsensical (since
scala.Long
is not a reference type and can never benull
), unless you're referring tojava.lang.Long
, which is a recipe for pain and confusion. Finally, even if you were dealing with a reference type (likeString
), you'd be better off writing the following, which is exactly equivalent:This method will return
None
if and only ifvalue
isnull
.To address your question, suppose we have the following method:
You shouldn't generally think in terms of passing an
Option[Long]
tofoo
, but rather of "lifting"foo
into theOption
viamap
: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 ofNullPointerException
-y problems. Usingmap
on theOption
allows you to perform computations on the value that may be in theOption
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 theOption
, but this usually isn't the idiomatic approach in Scala (except in cases where there really is a reasonable default value).As has already been mentioned getOrElse is probably what you're looking for in answering your question directly.
Please note also that to convert to an option you can simply:
myOption will now be Some(1)
myOption will now be None.
This method is already defined on Option[A] and is called get :
The problem is that calling get on None will throw a NoSucheElement Exception:
thus you will not gain any benefits from using an Option type.
Thus as stated before you can use getOrElse if you can provide a sensible default value or handle the Exception.
The idiomatic scala way would be using map or a for-comprehension
or
Option is way to localise side-effect (your function can return empty value). And good style to lift your computation to Option (Option is Monad with map & flatMap methods).
And extract value with manually processing of side effect:
You need to decide what happens when the option is
None
. Do you provide a default value?You could also throw an exception:
In case, refrain from using
null
, unless you have very good reasons to use it (opt.orNull
).