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.
Very popular usage pattern:
so you just use
mapin order to transform value if it’s defined.If you just want to use value, that is stored within an
Option, then just useforeach:As you can see,
Optionalso 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.