Saturday, October 8, 2011

Scala's Unit vs Java's void

The type of the result here is scala.Unit, which is Scala's analogue to void in Java. The main difference between Scala's Unit and Java's void is that Scala lets you write down a value of type Unit, namely (), whereas in Java there is no value of type void.
(In other words, just as 1, 2, and 3, are potential values of type int in both Scala and Java, () is the one and only value of type Unit in Scala. By contrast, there are no values of type void in Java.) Except for this, Unit and void are equivalent. In particular, every void-returning method in Java is mapped to a Unit-returning method in Scala.

scala> println("Hello, world!")
Hello, world!
unnamed2: Unit = ()

No comments: