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 ?
You can apply the annotation when you specify it as a constructor argument. Also, you may need to use a meta-annotation to restrict which target the annotation you’re using is applied to – see http://www.scala-lang.org/api/2.10.2-RC2/index.html#scala.annotation.meta.package
Your question about “relying on a default value” is somewhat unclear, though. Initialization using an underscore corresponds to assigning the value of the variable to null. What other default are you thinking of?