Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created August 15, 2011 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gclaramunt/1147238 to your computer and use it in GitHub Desktop.
Save gclaramunt/1147238 to your computer and use it in GitHub Desktop.
Scala's Option *CAN* save you from NullPointerExceptions
package demo
class SafeUnsafe {
def unsafe[T](x: =>T):Option[T]= try {
Option(x)
} catch {
case _ => None
}
def A(x:Int) = x+10
def B(x:Int) = x.toString
def C(s:String)=s+"!"
def D(s:String)="Hell yeah, "+s
def KaPow(s:String):String= throw new Exception("KaPow!")
def result(i:Int)=for (
a<- unsafe(A(i));
b<- unsafe(B(a));
c<- unsafe(C(b))
) yield D(c)
def noResult(i:Int)= for (
a<- unsafe(A(i));
b<- unsafe(B(a));
k<- unsafe(KaPow(b));
c<- unsafe(C(k))
) yield D(c)
//scala> result(1)
//res10: Option[java.lang.String] = Some(Hell yeah, 11!)
//scala> noResult(1)
//res11: Option[java.lang.String] = None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment