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
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.