When should I use Option.empty[A] and when should I use None in Scala?
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.
Short answer use None
if talking about a value for example when passing parameter to any function, use Option.empty[T]
when defining something.
var something = Option.empty[String]
means something
is None
for now but can become Some("hede")
in the future. On the other hand var something = None
means nothing. you can't reassign it with Some("hede")
compiler will be angry:
found : Some[String]
required: None.type
So, this means None
and Option.empty[T]
are not alternatives. You can pass None
to any Option[T] but you can't pass Some[T] to None.type