In his 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:
- Ban
null
from any of your code. Period. - If you're using a Java library that returns
null
, convert the result to a Scala Option.
One important rule when working with an Option
:
- Never call the
get
method on anOption
. Always access Options usingmap
orflatMap
, thefor
expression, or pattern matching.
As you can infer by this statement, it's important to note that Scala collection classes are created to work with Options. While using Option
with constructs like for-comprehensions and match expressions are nice, an enormous benefit of using Option
is that they're well supported by the methods of the collection classes.
2) Handling uninitialized Scala variables
There are times you will need to create uninitialized fields in a Scala class. When this need arises, use one of these approaches:
- Assign a default to the field that isn't null, such as an empty list, array, or vector.
- If the field can be accessed before its initialized, declare it as an
Option
, with a default value ofNone
.
3) Writing Scala methods
Rules for writing Scala methods:
- Never return
null
. - If you feel like returning a
null
value from a method, declare that the method will return an Option[T] (such as Option[String]), then return Some[T] and None from the method.
Benefits
Following these “rules” will eventually lead to the following benefits for you and your Scala code:
- You'll avoid null pointer exceptions (NPEs).
- Using Options and mapping functions eventually leads you to a different style of programming. There's a transformative effect that helps you learn a safer, functional style of programming.
Lest you think this is all a bit too much, as usual, I'll refer you to an article where the creator of the null value refers to the null as his “billion dollar mistake”:
I hope this brief tutorial on the use of null values and the Scala Option/Some/None pattern has been helpful. As mentioned, the meat of the article comes David Pollak's Beginning Scala book.