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 { 
            Option(x) 
        } 
        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(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
 at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
 at s...


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

hohonuuli

Developer

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

0 comments: