Created
August 15, 2011 17:07
-
-
Save fedesilva/1147210 to your computer and use it in GitHub Desktop.
Scala Option *will* save you from NullPointerException
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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