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

Arthur Ronald picture Arthur Ronald · Sep 3, 2011 · Viewed 19.7k times · Source

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 value manually by using the wildcard underscore, which acts like a default value, as follows

var name:String = _

I know, i know... I can define a constructor in the class definition, which takes as parameter our instance variable, so Scala does not force its initialization as shown below

class Person(var name:String) 

However, i need to declare it in the body because i need to use a Java annotation whose ElementType is FIELD or METHOD; that is, it can just be applied to either a instance variable or method declared in the body of our class.

Question: Why does Scala language require you initialize a instance variable - be it a default value _ or whatever you want - declared in the body of a class instead of relying on a default value ?

Answer

agilesteel picture agilesteel · Sep 3, 2011

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.