So Many Options, So Little Nulls and Nils

Malina Tran
Tech and the City
Published in
3 min readOct 11, 2016

One of the wonderful things about working with a new language is being introduced to a new framework or concept.

With Scala, I had the opportunity to learn about optional values, which was a bit of a doozy at first. An option is a container for representing values that may or may not be present (therefore it may represent one or no element). It is one way to get rid of and handle null.

Let’s break it down. Option[A] is a wrapper for an optional value of type A. If the value of A exists, then Option[A] is an instance of Some[A]; else, if nothing exists, the Option[A] is None. You can create an option simply by writing Some("Wrap it any type").

One of the most practical things about Option is applying the getOrElse method. The get method is used to get the value of an Option, see code snippet #1 below. If you were to apply get to a None, you would get an exception thrown. However, the getOrElse method is the equivalent of a try-catch statement since it handles the value of None and does so by passing a default argument. Check out code snippet #2 below — but beware of spoilers for Luke Cage, my latest and favoritest (sic) TV show.*

1
val harlemHero = Some(“Luke Cage”)
harlemHero.get
=> String = Luke Cage
2
val villain = None
villain.get
=> java.util.NoSuchElementException: None.get
villain.getOrElse("Cottonmouth is dead")
=> String = Cottonmouth is Dead

This blog post does an excellent job talking about other powerful ways to use Option for pattern matching and using methods to flatten and filter.

One of my low-key goals is to learn how to build iOS apps, although to be honest, I’ve heard enough grumblings about Xcode and the Apple Store to be slightly deterred. Still, I’ve started to concurrently learn Swift and was (pleasantly) surprised to learn about optionals for a similar use case: preventing your program from crashing.

Idiomatically, it looks very different. First things first, you can use a question mark ? to define an option and apply optional chaining. If you can guarantee a value, e.g. through a computed property, then you’re safe to use !. Otherwise, as a rule of thumb, any time you’re uncertain whether there is or will be a value, apply ?. By using ? , you can also chain both custom and built-in methods (e.g. append, count, etc.) on an object. You’d use this if you’re not relying on the value returned by that method because it won’t run if your object is nil.

To unwrap the value in an option, you’d also use an exclamation mark !. If the optional value is nil, then a runtime error is triggered. You should never unwrap something without doing some nil-checking, preferably by setting the option to a let variable. Based on the example below, if the option is not nil, then the variable powerMan will be set and we can use powerMan in our block of code.

In the last block of code, rather than double-nesting let variables to check that lukeCage and superPower are defined — I’ve set powerMan and bulletproof as variables on the same line, which is a cool thing you can do in Swift!

class MarvelHero {
// We're not sure if this variable will have a value
var superPower: String?
}
// Initializing lukeCage
lukeCage = MarvelHero()
// Setting variable to a value! Notice that we're option chaining.
lukeCage?.superPower = "Bulletproof"
// Handling and accessing options with values
if let powerMan = lukeCage, let bulletproof = powerMan.superPower {
print(bulletproof)
}

*I was not paid by Netflix to endorse Luke Cage, although let’s be real — I totally would, but even if I wasn’t (which I’m not), I still would anyway.

--

--