Created
July 23, 2016 15:38
-
-
Save JoolsF/8b63c545e4ab36cf3ac6093c18faf750 to your computer and use it in GitHub Desktop.
Try examples 1
This file contains 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
import scala.util.Try | |
val r = new java.util.Random | |
def randomBoolean = r.nextInt(8) != 0 | |
def stringOrException = if (randomBoolean) "Hello" else throw new RuntimeException | |
def stringOrException2(string: String) = if(randomBoolean) s"$string world" else throw new ArithmeticException() | |
def stringOrException3(string: String) = if(randomBoolean) s"$string human" else throw new NullPointerException | |
val getString: String = Try(stringOrException).getOrElse("There was a problem getting the string") // Hello | |
val getStrings: Try[Try[String]] = Try(stringOrException).map(x => Try(stringOrException2(x))) //Success(Success(Hello world)) | |
val getStrings2: Try[String] = | |
Try(stringOrException).flatMap(x => Try(stringOrException2(x))).flatMap(x => Try(stringOrException3(x))) //Success(Hello world human) | |
// This is the same as above | |
for { | |
s1 <- Try(stringOrException) | |
s2 <- Try(stringOrException2(s1)) | |
s3 <- Try(stringOrException3(s2)) | |
} yield s3 | |
// def recover[U >: T](f: PartialFunction[Throwable, U]): Try[U] | |
getStrings2 recover { | |
case r: RuntimeException => s"Exception has been thrown $r" | |
case a: ArithmeticException => s"Exception has been thrown $a" | |
case n: NullPointerException => s"Exception has been thrown $n" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment