04: Coding Scala Way – Null checks with Option-Some-None

Example #10: Null checks with “Option-Some-None”

Nulls in Scala is a code smell, and a better way to handle null values is with an “Option“, which has 2 sub classes “Some” that has a value and a “None” that does not have a value. Instead of checking for “myVal != null”, you can use “pattern matching” to deal with null values.

You can alse use methods like “isDefined” and “isEmpty“, but pattern matching shown above is cleaner.

getOrElse” is a handy method that takes a “default” value when the value is null.

Example #11: Option class supports map, flatMap, and filter

Example #12: Walking an object tree to check for null at each stage with “for comprehensions”

The “for-comprehension” is a syntactic sugar for a “flatMap” followed by a “map” as shown below

The “Option” class in Scala is “Monadic“, which means a way to compose data. Option supports composition via flatMap, and that’s what required to be a Monad.

You can create your own “Monadic” class as “MyMonad” shown below.

if you want to support “filter” function, then need to implement a “withFilter” function, and if looping is required a “forEach” function. We will look at “Functors, Applicative Functors, and Monads in a separate post.

500+ Enterprise & Core Java programmer & architect Q&As

Java & Big Data Tutorials