Archive for the ‘Scala’ Category

poking Unit with a stick (Scala)

December 22, 2008 5 comments

Scala has a thingy called Unit. For those coming from Java, Unit is similar to void but it is an actual type.

By my understanding, there’s only one actual instance of Unit ever and its value is ().

If you go to the Scala interpreter (type scala in a command prompt if you’ve downloaded Scala) you can assign Unit to a variable… er, um value in a few different ways.

One way is to simply create a value and assign () to it:
scala> val x = ()
x: Unit = ()

Another way is to make a value typed as Unit. You’re allowed to assign anything to it because pretty much any object in Scala can be automatically converted into Unit:
scala> val y: Unit = “turn me into Unit”
y: Unit = ()

I suppose the automatic conversion is because Scala methods return the value of the last expression. If Scala didn’t do this trick, we’d have to end every Unit-returning method with a gratuitous ().

Yet another way to end up with a Unit is to create a method without an assignment:
scala> def z(){“turn me into Unit too”}
z: Unit = ()

What’s this I say about a method without an assignment? Well the method z() I wrote above looks like a normal method to many folks (especially Groovy people). However, in Scala, most methods are created with an equals.
scala> def a() = “hello”
a: ()java.lang.String

Skipping the = is like automatically typing the method return as Unit, as if the z() method above were written as:
scala> def z(): Unit = {“turn me into Unit again”}
z: ()Unit

One weird thing I found with Unit is if I try to call getClass() on it:
scala> ().getClass
res1: java.lang.Class[_] = class scala.Predef$$anon$1

So it appears (), or Unit, is an anonymous inner class of something called object Predef.

Predef is a neato object. It pretty much is a way to get what appears to be a bunch of keywords and methods built into the Scala language, like println() and assertions.

Looking through the Predef source code, after being quite tickled by the ASCII art in the Scaladoc, I found the answer to another question I had about Unit – I had seen once in the Artima book unit with the lower case ‘u’. I originally thought it was a typo but tried it out in code and it seemed interchangeable. Line 36 of Predef, though the line is deprecated explains where unit (lower case ‘u’) comes from.

This was my experience digging into Unit in Scala. Try it out yourself and see what you can discover. Maybe you can uncover why ().getClass returns that weird Predef$$anon$1 thing.