Scala Options for Dummies, part 1

“Option” is Scala’s answer to values that may or may not be there. In the past, you might have just gone with assigning null to a variable when nothing is available. This leads to a lot of potential complications in code: null pointer exceptions, excessive null checking, or simply hard-to-find bugs.

First, what is Option? Option is a class that allows you to wrap a value. The Option itself has two possible representations: 1. Some; or 2. None. When the Option is “Some” you can get the actual value from it. When the Option is “None” you can go on your merry way.

balance_41848_md

Here’s a short example of manually creating an Option:

scala> val helloWorld = Option("Hello World")
helloWorld: Option[String] = Some(Hello World)

The nice thing about Option is that it interoperates easily with existing libraries that might return null. If you wrap a null value in an Option, it will automatically become “None.”

Here’s a little bit bigger example to help you understand why Option is so useful! You may not understand everything here, but this will hopefully give you a taste of why you should learn Option! And since you’ll be convinced to use Option after this, you’ll come back to the blog here for subsequent parts of this series!

Let’s say I write a method that takes a list of words and converts it to lowercase.

scala> def listToLower(l: List[String]) = l.map(_.toLowerCase)
listToLower: (l: List[String])List[String]

Now let’s say I pass a good list to it:

scala> listToLower(List("some","Words","in","a","list","WiTh","MiXeD","CASE"))
res13: List[String] = List(some, words, in, a, list, with, mixed, case)

So far so good. Now let’s say I accept a list passed in from somewhere else.

scala> listToLower(someListFromSomewhere)
java.lang.NullPointerException
  at $anonfun$listToLower$1.apply(:7)
  at $anonfun$listToLower$1.apply(:7)
  at scala.collection.immutable.List.map(List.scala:276)
  at .listToLower(:7)
  ... 33 elided

Oh my gosh! What?? What is in this list?

scala> someListFromSomewhere
res15: List[String] = List(Hello, my, null, null, name, is, null, Scott)

Crap! Now what do I do. I need to fix my method. I could do something like this:

scala> def listToLower(l: List[String]) = l.map(item => if(item != null) item.toLowerCase)
listToLower: (l: List[String])List[Any]

scala> listToLower(someListFromSomewhere)
res16: List[Any] = List(hello, my, (), (), name, is, (), scott)

Er….that’s not quite right. Now there’s a bunch of weird crap in the middle of the list that looks like “()”…Option can save the day here since passing null into an Option gives you a None.

scala> def listToLower(l: List[String]) = l.map(Option(_)).flatMap(x => x).map(_.toLowerCase)
listToLower: (l: List[String])List[String]

scala> listToLower(someListFromSomewhere)
res17: List[String] = List(hello, my, name, is, scott)

Wow! Let’s walk through this and see what happened!

Remember, this is what someListFromSomewhere looked like:

scala> someListFromSomewhere
res15: List[String] = List(Hello, my, null, null, name, is, null, Scott)

First, we took someListFromSomewhere and mapped each item to Option(_). This meant that all null values in the list turned into “None” values and all the other values turned into Some(…) values:

scala> someListFromSomewhere.map(Option(_))
res34: List[Option[String]] = List(Some(Hello), Some(my), None, None, Some(name), Some(is), None, Some(Scott))

Next we “flatMap” each item to itself. When you flatMap a “None” it gets ignored, so this weeds out the nones.

scala> someListFromSomewhere.map(Option(_)).flatMap(x => x)
res36: List[String] = List(Hello, my, name, is, Scott)

Alright, that looks great. Now we can perform the final step and map each item to a call to .toLowerCase in order to lower-case it.

scala> someListFromSomewhere.map(Option(_)).flatMap(x => x).map(_.toLowerCase)
res37: List[String] = List(hello, my, name, is, scott)

Like I said. All of this may not fully make sense now, but we’ll cover these things more in depth in future parts of “Scala Options for Dummies” so stay tuned to the blog here!

One thought on “Scala Options for Dummies, part 1

Leave a Reply

Your email address will not be published. Required fields are marked *