Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Option.empty[A] and when should I use None in Scala?

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
like image 621
cdmckay Avatar asked Mar 28 '16 06:03

cdmckay


People also ask

Why might you choose to use option rather than using null in Scala?

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.

What are option some and none in Scala?

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.

What is Scala none?

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.

How do I know if Scala is none?

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.


1 Answers

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.

like image 103
Łukasz Avatar answered Oct 26 '22 08:10

Łukasz