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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With