Why does Scala language require you initialize a instance variable instead of relying on a default value?

前端 未结 3 728
有刺的猬
有刺的猬 2021-02-02 10:24

Scala language requires you initialize your instance variable before using it. However, Scala does not provide a default value for your variable. Instead, you have to set up its

3条回答
  •  囚心锁ツ
    2021-02-02 10:46

    If you use code like the following you are declaring, that the name should be abstract:

    class A {
      var name: String
    }
    

    I suppose you already knew that. So your question is rather of the syntactical nature. The answer is consistency with other possible abstract candidates.

    Suppose you want to do something like this:

    class A {
       var variable: String = _ // variable has some default value (probably null)
       val value: String = _ // value cannot have any default values, since it cannot be reassigned later.
       def method: String = _ // method could return some default value (probably null)
       type theType = _ // what should the default type be? (Any perhaps?)
    }
    

    The last three examples don't even compile. Now suppose you want to do something like this:

    class A {
       var variable: String
       val value: String
       def method: String
       type theType
    }
    

    From my point of view, even someone who barely understands Scala sees only declarations. There is no way to misinterpret them, because there is nothing there else than declarations. The one and only confusion arises when you come from another language and assume for a second that there are some default values. But this confusion is gone as soon as you see the first example (the one with the default values). And btw your class has to be a part of an abstract hierarchy in order to be allowed to declare abstract members, so even if you are new to the language you already get some extra help from the compiler.

    I hope this answers your question and happy coding.

提交回复
热议问题