In Scala, when I want to set something to None
, I have a couple of choices: using None
or Option.empty[A]
.
Should I just pick one and use it consistently, or are there times when I should be using one over the other?
Example:
scala> def f(str: Option[String]) = str
f: (str: Option[String])Option[String]
scala> f(None)
res0: Option[String] = None
scala> f(Option.empty)
res1: Option[String] = None
In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.
An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
None is a subtype of Option type. Scala's best practices advise us to wrap the return value in the Option type in cases where the function may not have a return value.
We can test whether an Option is Some or None using these following methods: isDefined – true if the object is Some. nonEmpty – true if the object is Some. isEmpty – true if the object is None.
I would stick to None
whenever possible, which is almost always. It is shorter and widely used. Option.empty
allows you to specify the type of underlying value, so use it when you need to help type inference. If the type is already known for the compiler None
would work as expected, however while defining new variable
var a = None
would cause infering a
as None.type
which is unlikely what you wanted.
You can then use one of the couple ways to help infer what you need
@ var a = Option.empty[String]
a: Option[String] = None
@ var a: Option[String] = None
a: Option[String] = None
@ var a = None: Option[String] // this one is rather uncommon
a: Option[String] = None
Another place when compiler would need help:
List(1, 2, 3).foldLeft(Option.empty[String])((a, e) => a.map(s => s + e.toString))
(Code makes no sense but just as an example) If you were to omit the type, or replace it with None
the type of accumulator would be infered to Option[Nothing]
and None.type
respectively.
And for me personally this is the place I would go with Option.empty
, for other cases I stick with None
whenever possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With