Gary Sieling

Scala getOrElse example

The “getOrElse” function in Scala is a feature designed to help write code that avoids NullPointerExceptions.

scala> val x = null
x: Null = null

scala> x.toString
java.lang.NullPointerException
  ... 33 elided

Null is there to be like Java, but generally “None” is used instead:

val x = None
val y = Some(107)

This is similar to Java:

Integer x = null;
Integer y = 107;

The difference is that in Scala, the language gives you some nice options.

List(None, Some(107)).
  map( x => x.getOrElse(-1) )

res54: List[Int] = List(-1, 107)

You could also use a function (e.g. to log a warning):

List(None, Some(107)).
  map( x => x.getOrElse( { println("error") } )

You can also do useful things to handle unimplemented APIs – if you are writing code and you’re not sure if a branch will ever be used, you can avoid it by marking it as not implemented, with this awesome syntax:

List(None, Some(107)).
  map( x => x.getOrElse(???))

scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at $anonfun$1$$anonfun$apply$1.apply(:10)
  at $anonfun$1$$anonfun$apply$1.apply(:10)
  at scala.Option.getOrElse(Option.scala:120)
  at $anonfun$1.apply(:10)
  at $anonfun$1.apply(:10)
  at scala.collection.immutable.List.map(List.scala:272)
  ... 35 elided
Exit mobile version