Using nulls is not an Option

This blog post is dedicated to all people who hate nulls.
Why do NullPointerExceptions exist? Why do we have to work with nulls at all? Why? Or like Mourinho would say: Why? Why? WHY?

nlY1Wxv

Ladies, gentlemen, we, Scala programmers are null-haters. We work with Option type 🙂

What is an Option?

An Option is a parameterized type that can have two possible values:

  • Some(T)
  • None

For instance, an Option[Int] can be Some(1), Some(123456), None…

And what does this have to do with nulls?

We can encapsulate nulls in Option, and by doing so, instead of working directly with nulls, we can work with a type that is prepared to handle null values.

Option(null) === None

No more null pointers exploding, or checks of the kind if myValue == null.

nlY1Wxv

Imagine the typical method that returns a value from a map:

val m =
  Map(
    1 -> "head",
    2 -> "shoulders",
    3 -> "knees",
    4 -> "toes"
  )

If we didn’t work with Option, we would have to check if a given key exists before asking for its value.

if(m.contains(1))
  println("I'm pointing at my: " + m(1))
else
  println("I'm actually pointing to nowhere")

However, we can query the map for a value encapsulated in an Option, and in case it doesn’t exist, that Option will be None.

m.get(1) //Returns Some("head")
m.get(5) //Returns None

How can we work with Option type?

There are several ways to work with this gentle structure.

First of all, we have getOrElse method. This method returns either the value of the Option (in case it is Some) or what is passed as an argument to this method.
A simple example:

m.get(1).getOrElse("belly button")

Another possibility is to use Pattern Matching:

m.get(1) match {
  case Some(bodyPart) =>
    println("Girl, look at my " + bodyPart)
  case None =>
    println("I’m sexy and I know it")
}

We can also work with fold method. Fold method, unlike getOrElse method (and just as pattern matching), allows us to apply some function to the returned method. The first argument of the function (called ifEmpty) gets the result that is to be returned in case the Option is None. The second argument gets a function that must be defined to know which result is to be returned in case the Option has a value.

m.get(1).fold(
  ifEmpty = println("I don’t feel like dancing")){
  step => println(s"I broke my $bodyPart while dancing La Macarena")
}

And for those of you who are functional lovers (warm greetings to you all), we shall not forget that an Option is a monad and thus, transformations can be made, for instance, with map, flatmap or with just a spoonful of syntactic sugar, for-comprehension:

for {
  first <- m.get(1)
  second <- m.get(2)
} yield s"I’ll start pointing my $first and then my $second"

There are other similar structures that will be detailed in future posts: Either, Try, … but let things take their course.

So, remember: if you use Option children smile, little birds sing and nulls disappear 🙂

nlY1Wxv

Un comentario en “Using nulls is not an Option

Deja un comentario