Created
August 15, 2011 17:20
-
-
Save gclaramunt/1147238 to your computer and use it in GitHub Desktop.
Scala's Option *CAN* save you from NullPointerExceptions
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
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