Why does this compile
scala> import scala.concurrent.Future
import scala.concurrent.Future
scala> val f: Unit = Future.successful(())
f: Unit = ()
I expected the compiler to complain about the assignment.
This is called "Value Discarding". Citing the scala specification (6.26.1):
Value Discarding
If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }.
In other words, any value, whatever its type, is implicitly converted to Unit
, effectively discarding it.
It you want to be warned about such discarding (which can in some cases hide a bug), you can pass the -Ywarn-value-discard
option to the compiler. You'll then have to explicitly return ()
every time you call a method only for its side effect, but that method does return a non-Unit value.
The compiler is fine since applying f will only execute the call
val f: Unit = Future.successful(())
and the return value will go into the nirvana.
Basically this is the same as:
val f: Unit = {
Future.successful(())
()
}
If the compiler don't find the Unit it expects in the last value of the method it will put it there.
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