Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try and getOrElse scala

Tags:

scala

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

In the case where here_a is not found, this is not falling back to here_b. Why is the .getOrElse 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")

Edit

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 json file may be found in one of two possible locations. I thus wish to try the first location and if a java.io.FileNotFoundException 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 spark and I forgot to repackage in between testing. sbt package was all that was required. :-/

like image 413
LearningSlowly Avatar asked Oct 24 '16 06:10

LearningSlowly


3 Answers

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

scala> 

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

like image 144
Andrew James Ramirez Avatar answered Sep 23 '22 21:09

Andrew James Ramirez


Try() returns either a Success(x) or a Failure(e), where x is the successful value returned and e is the exception that was thrown. getOrElse() unwraps the Success or supplies a default value.

If you're not getting the "OrElse" then your code isn't throwing a catchable exception.

like image 44
jwvh Avatar answered Sep 26 '22 21:09

jwvh


It works as you expect it should.

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40).
Type in expressions for evaluation. Or try :help.

scala> val label = Try(throw new RuntimeException("here_a")).getOrElse("here_b")
label: String = here_b

Please provide more context in your question if you feel this answer is insufficient.

like image 25
Synesso Avatar answered Sep 22 '22 21:09

Synesso