Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a Try[Try[Unit]] value be assigned to Try[Unit]?

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 ?

like image 924
Francis Toth Avatar asked Jan 07 '23 18:01

Francis Toth


1 Answers

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.

like image 175
Iulian Dragos Avatar answered Jan 16 '23 04:01

Iulian Dragos