The definition of Try is already familiar because of its similarity to Either, and so are the ways of creating an instance of it. For starters, we can use the constructors of the case classes to create instances directly:
scala> import scala.util._
import scala.util._
scala> Success("Well")
res1: scala.util.Success[String] = Success(Well)
scala> Failure(new Exception("Not so well"))
res2: scala.util.Failure[Nothing] = Failure(java.lang.Exception: Not so well)
The idea behind Try is that it can be used in scenarios where an exception would normally be thrown. Hence, the constructors we just mentioned would normally form the following pattern:
try Success(System.console().readLine()) catch {
case err: IOError => Failure(err)
}
This will end with the result of the try block being wrapped in Success and the catch exception wrapped in Failure. Again, stdlib already has this pattern implemented in the companion object of Try. The apply method takes a single by-name parameter for the try block, like so:
Try(System.console().readLine())
And then catches all NonFatal exceptions.
It is common to provide multiline blocks wrapped in curly braces as a parameter for the Try constructor to makes it appear like it's a language feature:
scala>val line = Try {
val line = System.console().readLine()
println(s"Got $line from console")
line
}
This constructor is so common that it covers the absolute majority of use cases.
Now, let's take a look at how we can get back the value from an instance of Try.