Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala best practices: simple Option[] usage

Tags:

null

scala

As a Java-to-Scala switcher, I routinely find myself rewriting null handling stuff like

val itemOpt: Option[Item] = items.get(coords) // "items" is something like a Map
if (itemOpt.isDefined) {
  val item = itemOpt.get
  // do something with item, querying item fields a lot of times, for example
  if (item.qty > 10) {
    storeInVault(item.name, item.qty, coords)
  } else {
    storeInRoom(item)
  }
}

I guess it looks ugly and it really looks like a piece of code rewritten from Java's:

Item item = items.get(coords);
if (item != null) {
  // do something with item, querying item fields a lot of times, for example
}

It also looks ugly in Java, but at least it's one line less. What is the best practice to handle such simple cases in Scala? I already know of flatMap and flatten to handle collections of Option[Stuff], and I know of getOrElse to handle default values. I dream of something like:

items.get(coords).doIfDefined(item =>
  // do stuff with item
)

but I don't see anything like that in Option API.

like image 383
GreyCat Avatar asked Dec 18 '12 20:12

GreyCat


People also ask

What is Option [] in Scala?

The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.

Why do we use option in Scala?

Scala's Option is particularly useful because it enables management of optional values in two self-reinforcing ways: Type safety – We can parameterize our optional values. Functionally aware – The Option type also provides us with a set of powerful functional capabilities that aid in creating fewer bugs.

How do you use some and options 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.

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.


1 Answers

Very popular usage pattern:

val item: Option[Int] = None
val result = item map (_ + 1) getOrElse 0

so you just use map in order to transform value if it's defined.

If you just want to use value, that is stored within an Option, then just use foreach:

item foreach { it =>
    println(it)
}

As you can see, Option also supports many collection methods, so you actually don't need to learn new API. You can just treat it as a collection with either 1 or 0 elements.

like image 162
tenshi Avatar answered Oct 09 '22 21:10

tenshi