Skip to content

Instantly share code, notes, and snippets.

@ayoub-benali
Created November 1, 2014 18:33
Show Gist options
  • Save ayoub-benali/dabed51e64ca4b4ab160 to your computer and use it in GitHub Desktop.
Save ayoub-benali/dabed51e64ca4b4ab160 to your computer and use it in GitHub Desktop.
Try's trap
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)
@missingfaktor
Copy link

Not sure what's so surprising about this.

In the first case, this is what happens:

Try{1+1}.map{x => Try{x/0}}

// becomes 

Try{1+1}.map{x =>
  Try{x/0}
  () // because you explicitly annotated it for `Unit`.
}

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. Since x/0 will fail, you get a failure out.

@ayoub-benali
Copy link
Author

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