Why assign Try [Unit] to Try [Unit]?

I just came across a very strange behavior. Here is the code:

// So far everything 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, since (as far as I know) Try[Try[Unit]]cannot be assigned Try[Unit], but in this case it seems that a Try{}will automatically convert to Unit( ()). How is this possible?

+4
source share
2 answers

Any type can be adapted to Unitin the right context, simply reducing the value. In this case, the expression is parsed as follows:

val x: Try[Unit] = Try {
  Try {}
  () // adapting the result to Unit
}

You can warn about problems with the scala compiler for such cases by passing -Ywarn-value-discard.

+6

? Unit: val a: Unit = 2.

, :

def test: Unit = {
  Try{}
}

, Try {}

+2

Source: https://habr.com/ru/post/1625854/


All Articles