Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created July 23, 2016 15:38
Show Gist options
  • Save JoolsF/8b63c545e4ab36cf3ac6093c18faf750 to your computer and use it in GitHub Desktop.
Save JoolsF/8b63c545e4ab36cf3ac6093c18faf750 to your computer and use it in GitHub Desktop.
Try examples 1
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