Success and Failure
In this page:
Success and Failure
Success(value) and Failure(exception) are Try's two possible outcomes, matched with pattern matching just like Some/None. .getOrElse and .map work on Try the same way they do on Option, transforming a Success's value while leaving a Failure unchanged. This lets you write error-handling code that reads much like ordinary Option-based code.
Note: Try's map/getOrElse/pattern-matching API deliberately mirrors Option's, so switching between the two feels familiar.
Example: Success and Failure
import scala.util.{Try, Success, Failure}
object Main extends App {
val results = List(Try(10 / 2), Try(10 / 0))
results.foreach {
case Success(value) => println(s"Got: $value")
case Failure(ex) => println(s"Failed: ${ex.getClass.getSimpleName}")
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: