Scala: Why can I convert Int to Unit?
Asked Answered
R

3

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.

Roswell answered 18/8, 2010 at 14:51 Comment(0)
E
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; () }.

...

Eclectic answered 18/8, 2010 at 15:16 Comment(1)
Note that you can make a warning for this by using scalacOptions += "-Ywarn-value-discard" in SBT configuration.Monatomic
P
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
}
Pavel answered 18/8, 2010 at 15:20 Comment(1)
It's not really necessary, though if you usually want to ignore return values it is more convenient than doing so explicitly.Sensualism
S
-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.

Shanty answered 18/8, 2010 at 15:14 Comment(1)
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?Archbishopric

© 2022 - 2024 — McMap. All rights reserved.