LearningSlowly LearningSlowly - 1 year ago 81
Scala Question

Try and getOrElse scala

val label = Try("here_a").getOrElse("here_b")

In the case where
is not found, this is not falling back to
. Why is the
not functioning?

Thanks @jwvh. These values are sting files paths and thus the exception is the following
Exception in thread "main" java.io.FileNotFoundException:

As per Andrew James Ramirez's comment I tried this but issue persists.

Try(throw new Exception("FAIL here_a")).getOrElse("here_b")

I have also tried

Try(throw new Exception("FileNotFoundException here_a")).getOrElse("here_b")


It seems I may have oversimplified this question for SO. Some more context. The string is actually a file path. Perhaps this is making a difference?

Effectively, a
file may be found in one of two possible locations. I thus wish to try the first location and if a
is returned, fall back on the second location. This is what I presently have:

val input_file = Try(throw new Exception("FAIL location_a/file_a.json")).getOrElse("location_b/file_a.json")

Edit V2

I am embarrassed to say that I found the simple error. I am running this scala code on
and I forgot to repackage in between testing.
sbt package
was all that was required. :-/

Answer Source

I think you misunderstood Try. and .getOrElse

Definition of Try :

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala.util.Either type.

scala> Try("here_a")
res1: scala.util.Try[String] = Success(here_a)

scala> Try("here_a").get
res2: String = here_a

scala> Try(throw new Exception("FAIL here_a")).getOrElse("here_b")
res3: String = here_b


It only fails if you throw Exception. null is still a value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download