I noticed that in one of my exercises I did the following.
if ( something)
Option(data)
else
None
And it still worked. What is the difference between Option(data) and Some(data) ?
It seems that for the simple cases they are equal == .
I noticed that in one of my exercises I did the following.
if ( something)
Option(data)
else
None
And it still worked. What is the difference between Option(data) and Some(data) ?
It seems that for the simple cases they are equal == .
Constructing with Option(x) will do a null-check on x, Some(x) does not and may therefore contain null as a value.
roughly:
Option(x) = if (x == null) None else Some(x)
Cheers,
Enno.
option(null) == Nonesome(null) == wrapping a null in an option
Gesendet: Dienstag, 21. März 2017 um 17:09 Uhr
Von: jimka <[email protected]>
Betreff: [Scala Users] [Question] What’s the difference between Option and Some jimka
March 21
I noticed that in one of my exercises I did the following.
if ( something)
Option(data)
else
None
And it still worked. What is the difference between Option(data) and Some(data) ?
It seems that for the simple cases they are equal == .</p>
Visit Topic or reply to this email to respond.
You are receiving this because you enabled mailing list mode.
To unsubscribe from these emails, click here.
Option[A]
is a type. Some(a): Option[A]
and None: Option[Nothing]
are instances of the type. The companion object for Option has an apply() method which is basically
def apply(a: A): Option[A] = if (a == null) None else Some(a)
So if a
isn’t null then Option(a) == Some(a)
and if it is null then Option(a) == None
.
Note that you can get yourself into trouble sometimes putting None first in certain constructs because Scala can’t figure out what the type A
should be. An alternative to None
that gives Scala more type information is Option.empty[String]
(or Int
or whatever type A
you are after).
Hello,
Alternatively to Option.empty[A], you could also write None: Option[A].
Best, Oliver
Hi @jimka
I found a very good Description about Option and how to work with in the effective Scala - Option from Twitter.
Think Option is a Collection with one or zero item.
Greetings Roebi
Also
Option(null) == None
But
Some(null) == Some(null)
Very important when dealing with Java data. Use Option() to convert
possible nulls into Options