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
0 comments:
Post a Comment