Reading values from Try

There are multiple ways to approach this task. It is possible to use methods similar to isDefined and isEmpty for Option, which allow for a null-pointer checking style:

if (line.isSuccess) println(s"The line was ${line.get}")
if (line.isFailure) println(s"There was a failure")

Obviously, this approach suffers from the same issue that Option does – if we forget to check that the result is a Success before extracting it, calling .get will throw an exception:

scala> Try { throw new Exception("No way") }.get
java.lang.Exception: No way
at .$anonfun$res34$1(<console>:1)
at scala.util.Try$.apply(Try.scala:209)
... 40 elided

To avoid throwing an exception just after catching it, there is a version of get that allows us to provide a default argument for the case if Try is a Failure:

scala> Try { throw new Exception("No way") }.getOrElse("There is a way")
res35: String = There is a way

Unfortunately, there are no predicate-taking methods like there were for Option. The reason for this is that Try was adopted from Twitter's implementation and was first added to Scala's standard library in version 2.10. 

The foreach callback is still available, though, and allows us to define a function that will be executed on the value of the Success:

scala> line.foreach(println)
Hi, I'm the success!

The foreach method brings our discussion to the effect side of Try.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.172.93