Search code examples
classscalastaticlanguage-designstatic-members

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


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.


Solution

  • I also posted this question on scala users google group and Bill Venners one of the authors of "Programming in scala" reply had some insights.

    Take a look at this: https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/6vZJgi42TIMJ and https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/oTrLFtwGjpEJ

    Here is an excerpt:

    I think one goal was simply to be simpler, by having every value be an object, every operation a method call. Java's statics and primitives are special cases, which makes the language more "complicated" in some sense.

    But another big one I think is to have something you can map Java's statics to in Scala (because Scala needed some construct that mapped to Java's statics for interop), but that benefits from OO inheritance/polymorphism. Singleton objects are real objects. They can extend a superclass or mix in traits and be passed around as such, yet they are also "static" in nature. That turns out to be very handy in practice.

    Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) http://www.artima.com/scalazine/articles/goals_of_scala.html

    Here is an excerpt:

    First, we wanted to be a pure object-oriented language, where every value is an object, every operation is a method call, and every variable is a member of some object. So we didn't want statics, but we needed something to replace them, so we created the construct of singleton objects. But even singleton objects are still global structures. So the challenge was to use them as little as possible, because when you have a global structure you can't change it anymore. You can't instantiate it. It's very hard to test. It's very hard to modify it in any way.

    To Summarize:

    From a functional programming perspective static members are generally considered bad (see this post by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.

    Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop).