Why doesn't Scala have static members inside a class?

numan salati picture numan salati · Sep 4, 2011 · Viewed 23.9k times · Source

I know you can define them indirectly achieve something similar with companion objects but I am wondering why as a language design were statics dropped out of class definitions.

Answer

Kevin Wright picture Kevin Wright · Sep 5, 2011

The O in OO stands for "Object", not class. Being object-oriented is all about the objects, or the instances (if you prefer)

Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism. Simply put, statics aren't object-oriented.

Scala, on the other hand, is object oriented. Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.

They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.

Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated. These things have no place in any well-designed language that wishes to describe itself as object-oriented.


Concerning why it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:

The way I look at it, though, is that singleton objects allow you to do the static things where they are needed in a very concise way, but also benefit from inheritance when you need to. One example is it is easier to test the static parts of your program, because you can make traits that model those parts and use the traits everywhere. Then in the production program use a singleton object implementations of those traits, but in tests use mock instances.

Couldn't have put it better myself!

So if you want to create just one of something, then both statics and singletons can do the job. But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.

In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.