August 2018
Intermediate to advanced
380 pages
10h 2m
English
Another example of a data structure that is characteristic of functional languages is an Option. An Option can either contain a value or be empty. You can think of it as an abstraction of the notion of the null pointer in Java or C++. The advantage here is that the programmer no longer needs to remember that some methods return a null. The methods that may, or may not, result in a value will return an Option[A] to signify this possibility, just as in the case of Try.
For example, consider a method that returns the name of the user by their ID. Some IDs won't map to a user. Hence, we can model the scenario where we can't return a user that does not exist as follows:
def getUserName(id: Int): Option[String] = if (Set(1, 2, 3).contains(id)) ...