21

I've recently started playing with Scala (2.8) and noticed the I can write the following code (in the Scala Interpreter):

scala> var x : Unit = 10 x : Unit = () 

It's not obvious what's going on there. I really didn't expect to see any implicit conversion to Unit.

3 Answers 3

34

See section "6.26.1 Value Conversions" in the Scala Language Specification version 2.8:

...

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; () }.

...

Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can make a warning for this by using scalacOptions += "-Ywarn-value-discard" in SBT configuration.
15

Anything can be converted to Unit. This is mostly necessary to support side-effecting methods which nonetheless return values, but where the return value is often ignored. For instance

import java.util.{List =>JList} def remove2[A](foo: JList[A], a1:A, a2:A):Unit = { foo.remove(a1) foo.remove(a2) //if you couldn't convert the (usually pointless) return value of remove to Unit, this wouldn't type } 

1 Comment

It's not really necessary, though if you usually want to ignore return values it is more convenient than doing so explicitly.
-2

Well, anything can be converted to unit (which is its purpose). You can think of Unit as unit in the lattice of (sub)types, which means it is a supertype of everything. See Wikipedia article.

1 Comment

It's not clear to me exactly what you mean here: Unit is not actually the least element of the type lattice in Scala, which is the type Any. Unit does not actually have any subtypes in Scala as far as I can tell, it is defined as "final class Unit extends AnyVal". mkneissl's answer above seems to give the real reason this works - implicit conversion. Did you mean something specific in saying it the lattice of (sub)types?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.