Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

Option

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)) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content