Question

Possible Duplicate:
Why are singleton objects more object orientated?

Why does Scala have language support for the Singleton anti-pattern? If Scala had inherited the static keyword from Java, what legitimate use cases of the object keyword would be left?

Was it helpful?

Solution

There is an up-front difference at least, in that an object in Scala actually is an object (i.e. an instance), rather than in Java where it's just methods called on the class itself.

This means that it avoids one of the major complaints about singletons - since it is an instance, it can be passed around and wired into methods, and so can be swapped out for other implementations during tests, etc. If anything it's syntactic sugar for the recommended alternative to singletons - having a class with a getInstance() method returning the default, single instance.

That said, I consider that the Singleton anti-pattern is more about design than it is language features. If you structure your code base such that some monolithic dependency is implicitly wired throughout most of the classes, then you're going to have issues changing it - regardless of the language features.

There are legitimate use cases for objects in Scala (e.g. using case objects for messages to Actors, or having several of them extend a sealed trait as an alternative to enums). The language feature can be abused, but to my mind it's less abusable than Java's static, and more useful.

OTHER TIPS

Singletons without state aren't that bad. I see objects (in scala) as modules to put functions (behaviour) in.

If you use an object to hold state, that's a case where singletons are a disaster, because there may not be a way to clear it up and that's one of the prime examples of singletons being an anti-pattern. An object without mutable state and with pure functions is much less prone to causing pain in this respect, here's an example:

object StringSerializer extends Serializer[String] {
  // Implementation goes here.
}

In this case there's no need to new up an instance of the Serializer, which makes for simpler code and likely better performance.

For example type classes. The difference between static classes and singletons is, that singletons are objects and can be passed around as parameters. This code for example could not be built with static classes:

trait TypeClass[A] {
  def method(x: A): A
}

implicit object IntTypeClass extends TypeClass[Int] {
  def method(x: Int) = x*x
}

def foo[A](x: A)(implicit tc: TypeClass[A]) = tc.method(x)

scala> foo(2)
res0: Int = 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top