I've just came across a very weird behavior. Here's the code:
// So far everything's fine
val x: Try[Try[Unit]] = Try(Try{})
x: scala.util.Try[scala.util.Try[Unit]] = Success(Success(()))
// Compilation error should happen here
val x: Try[Unit] = Try(Try{})
// Wuut ?
x: scala.util.Try[Unit] = Success(())
I was expecting a compilation error here, as (as far as I know) a Try[Try[Unit]]
should not be assignable to a Try[Unit]
, but in this case it seems that a Try{}
is automatically converted to a Unit
(()
). How is that possible ?
Any type can be adapted to Unit
in the right context by simply dropping the value. In this case, the expression is parsed like this:
val x: Try[Unit] = Try {
Try {}
() // adapting the result to Unit
}
You can make the scala compiler issue warnings for such cases by passing -Ywarn-value-discard
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With