Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Future[Unit] to Unit

Tags:

scala

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.

like image 855
Bomgar Avatar asked Sep 22 '15 09:09

Bomgar


3 Answers

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.

like image 81
Régis Jean-Gilles Avatar answered Oct 18 '22 18:10

Régis Jean-Gilles


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.

like image 37
M. Reif Avatar answered Oct 18 '22 17:10

M. Reif


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.

like image 29
thoredge Avatar answered Oct 18 '22 17:10

thoredge