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

前端 未结 5 1447
忘掉有多难
忘掉有多难 2020-12-12 22:05

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 o

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 22:30

    These are the things that pop into my head when I think about how statics could complicate things:

    1) Inheritance as well as polymorphism would require special rules. Here is an example:

    // This is Java
    public class A {
      public static int f() {
        return 10;
      }
    }
    
    public class B extends A {
      public static int f() {
        return 5;
      }
    }
    
    public class Main {
      public static void main(String[] args) {
        A a = new A();
        System.out.println(a.f());
        B b = new B();
        System.out.println(b.f());
        A ba = new B();
        System.out.println(ba.f());
       }
    }
    

    If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like @Override annotation, which is of course optional and the friendly "The static method f() from the type A should be accessed in a static way" warning. This leads us to

    2) The "static way" of accessing stuff is a further special rule, which complicates things.

    3) Static members cannot be abstract. I guess you can't have everything, right?

    And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.

提交回复
热议问题