Created
November 1, 2014 18:33
-
-
Save ayoub-benali/dabed51e64ca4b4ab160 to your computer and use it in GitHub Desktop.
Try's trap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.Try | |
// isn't the following line supposed not to compile ? | |
val foo: Try[Unit] = Try{1+1}.map{x => Try{x/0}} | |
// foo: scala.util.Try[Unit] = Success(()) | |
val foo: Try[Unit] = Try{1+1}.flatMap{x => Try{x/0}} | |
// scala.util.Try[Unit] = Failure(java.lang.ArithmeticException: / by zero) |
I got your point, it guess it is because there is an implicit conversion by the compiler from any type to Unit ?
it is funny that the error is caught by the compiler in this case:
val foo: Try[Unit] = {val r= Try{1+1}.map{x => Try{x/0}}; r}
<console>:8: error: type mismatch;
found : scala.util.Try[scala.util.Try[Int]]
required: scala.util.Try[Unit]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure what's so surprising about this.
In the first case, this is what happens:
You map over success with a function that yields a success.
In second case, since it's a
flatMap
and the first operation was successful, it's second case's success or failure that will decide net success or failure. Sincex/0
will fail, you get a failure out.