Skip to content

Instantly share code, notes, and snippets.

View rdecaire's full-sized avatar

Robert DeCaire rdecaire

  • Inflection Group
  • Toronto
View GitHub Profile
val recoveryTry: PartialFunction[Throwable, Try[String]] = {
case e: Exception => Success("I'm the default response!")
}
tFail.recoverWith(recoveryTry)
// scala.util.Try[String] = Success(I'm the default response!)
val tFail: Try[String] = Try(throw new Exception("I failed!"))
tFail.recover {
case e: Exception => "This made me fail: " + e.getMessage
}
// scala.util.Try[String] = Success(This made me fail: I failed!)
val tFail: Try[String] = Try(throw new Exception("I failed!"))
// tFail: scala.util.Try[String] = Failure(java.lang.Exception: I failed!)
val tThrow = tFail.failed
// tThrow: scala.util.Try[Throwable] = Success(java.lang.Exception: I failed!)
val tSuccess = Try("Everything okay!")
// tSuccess: scala.util.Try[String] = Success(Everything okay!)
val tThrow2 = tSuccess.failed
// tThrow2: scala.util.Try[Throwable] = Failure(java.lang.UnsupportedOperationException: Success.failed)
t1.fold(f => "failed", s => s)
// String = hello
import scala.util.{Success, Failure}
t1 match {
case Success(string) => string
case Failure(t) => "Got a throwable: " + t.getMessage
}
// String = hello
t2.get
// java.lang.Exception: let's fail instead
for {
s1 <- t1
s2 <- t2
s3 <- t3
} yield s1 + " " + s3
// scala.util.Try[String] = Failure(java.lang.Exception: let's fail instead)
val t1 = Try("hello")
val t2 = Try(throw new Exception("let's fail instead"))
val t3 = Try("world")
val t4 = t1.flatMap(a => t2.flatMap(b => t3.map(c => a + " " + c)))
// t4: scala.util.Try[String] = Failure(java.lang.Exception: let's fail instead)
import scala.util.Try
// Try is not imported by default
val t1: Try[String] = Try("hello")
// t1: scala.util.Try[String] = Success(hello)
val t2 = Try(throw new Exception("let's fail instead"))
// t2: scala.util.Try[Nothing] = Failure(java.lang.Exception: let's fail instead)
r.swap.map(_.toUpperCase)
// scala.util.Either[User,String] = Left(User(Sam,24))