Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.
Table of Contents
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.”Back to top
For a variety of reasons, including removing
null values from your Scala code, you want to use what I call the Option/Some/None pattern. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.17, “How to declare a variable (var) before using it in try/catch/finally.”
You want to use an object in a
try block, and need to access it in the
finally portion of the block, such as when you need to call a
close method on an object.
Scala FAQ: How do I parse a number (
Float, etc.) from a
String in Scala?
to* methods that are available on a
String (courtesy of the Scala
This image comes from this article. I don’t like the
fold approach at all, but it shows a nice way to use
map instead of match/case when processing an
Option in Scala.
Today I’m sharing some examples of the Scala
None syntax. These examples will show how to use an
Option for the
var fields in a Scala class. Then I’ll show how to set those
Option fields, and then get the values from the
To get started, we’ll need a little case class to represent an
Again not much time for a discussion today, but if you’re looking for an example of how to declare, set, and use
Option fields in Scala, I hope this source code is helpful:
Summary: How to properly use the Scala Option/Some/None idiom to initialize empty var fields -- and specifically how not to use null values for the same purpose.
When you get started in the Scala world, you quickly learn that
null values are a bad thing. Scala makes it easy to replace
null values with something better, and that something better is what I call the Option/Some/None pattern (or idiom).
In his excellent book, Beginning Scala, David Pollak provides a series of statements that can be considered as a recipe for avoiding the use of null values in your Scala code. I've organized his statements here in the following three sections.
1) General rules about null and Option
We begin with the following general rules regarding the use of null values in Scala code: