Java Reference
In-Depth Information
Option
Another data structure that you'll be familiar with is Option. It's Scala's version of Java 8's
Optional, which we discussed in chapter 10 . We argued that you should use Optional when
possible to design better APIs, in which just by reading the signature of a method users can tell
whether or not they can expect an optional value. It should be used instead of null when possible
to prevent null pointer exceptions.
You saw in chapter 10 that you could use Optional to return the insurance's name of a person if
their age is greater than a minimum age, as follows:
public String getCarInsuranceName(Optional<Person> person, int minAge) {
return person.filter(p -> p.getAge() >= minAge)
.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
}
In Scala you can use Option in a way similar to Optional:
def getCarInsuranceName(person: Option[Person], minAge: Int) =
person.filter(_.getAge() >= minAge)
.flatMap(_.getCar)
.flatMap(_.getInsurance)
.map(_.getName).getOrElse("Unknown")
You can recognize the same structure and method names apart from getOrElse, which is the
equivalent of orElse in Java 8. You see, throughout this topic you've learned new concepts that
can be directly applied to other programming languages! Unfortunately, null also exists in Scala
for Java compatibility reasons and its use is highly discouraged.
Note
In the previous code you wrote _.getCar (without parentheses) instead of _.getCar() (with
parentheses). In Scala parentheses aren't required when calling a method that takes no
parameters.
Search WWH ::




Custom Search