Safe-dereference operator in Scala

by 7/15/2010 11:48:00 AM 0 comments
I've always loved Groovy's null safe operators (i.e ?.) and wanted something similar in Scala. In keeping with Scala's preference of using Option for managing null's, this little object seems to do the trick:
object SafeOption { 
    def apply[A](x: => A):Option[A] = {
        try { 
        catch { 
            case _ => None 
This allows me to try pretty much anything and have it safely handled. For example:
// Straight Scala
scala> val a = Option(Nil.head)
java.util.NoSuchElementException: head of empty list
 at scala.collection.immutable.Nil$.head(List.scala:386)
 at .(:5)
 at .()
 at RequestResult$.(:9)
 at RequestResult$.()
 at RequestResult$scala_repl_result()
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(
 at java.lang.reflect.Method.invoke(
 at s...

// With 'safe-dereferencing'
scala> val a = SafeOption(Nil.head)
a: Option[Nothing] = None

Brian Schlining


Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.