Tuesday, September 02, 2008

No More Statics!

As I read more about Scala, I'm running across a lot of things that I like. In Scala, there are no static members: no static methods; no static fields. Instead, Scala has so-called "singleton" objects. These singleton objects are globally accessible, though their instance methods and fields are still subject to access restriction. This is great because it exposes what we all knew all along: that static fields and methods in Java are really just global variables and functions. Granted, they are access-controlled, namespaced globals, but they're still globals.

Since each class' singleton object is in fact an object, it can subclass another object or mix in traits, just like objects that are spawned by a class. The singleton object has the same rights as any other object in the system.

In addition, a singleton object can share a name with a class; if it does so, they can access each other's private data. I'm not sure yet, but I assume that this is how Scala accesses static members of Java classes - it creates a singleton object that doesn't derive or mix in anything, but turns all the static methods and fields of the Java class into instance members of the singleton object.

2 comments:

Marc said...

Statics in languages like Java aren't bad, it is specifically mutable static variables that are bad. Every other type of static is to be encouraged, I say.

Consider, a non-mutable static variable is normally called a constant, which sure beats magic hard-coded values. A static function that doesn't operate on mutable static variables is as close to a pure function as one can get in Java (It can always manipulate system state, so it isn't truly pure). Static inner classes advertise that they don't muck with another classes internals, not without explicitly being passed a reference, that is.

I do dislike that one can't just have a free function (a la C++) in Java, rather we have to tie it to a specific form of a namespace called a "class".

You should go deeper into how static classes work in Scala, I'm not clear on what they provide. Maybe add some sample code?

Daniel Yankowsky said...

A more recent post has some sample code that expands on the ideas here. Check it out!