Assume this Java code:
public class A {
public A(String g) {
x += g.length();
}
private int x = 0;
}
If I create an instance of A, like this:
A a = new A("geo");
after this call, the value of x will be 3. What am I doing wrong in my Scala code?
class A(val g:String) {
x += g.length
var x:Int = 0
}
object x extends Application {
val x = new A("geo")
println(x.x)
}
This prints 0. I assumed that when the compiler reaches the var x:Int = 0, the body of the main constructor has ended. Am I wrong? How else could you declare instance variables in Scala ( assuming I don’t want them in my constructor ) ?
Keep in mind that your code translates into something similar (but not exactly) to this:
But vars defined in (non-constructor) methods get translated into actual local variables.
Not sure if this explains the reasoning so much as highlights one of the differences.
EDIT – Changed “translation” from scala to java for clarity and ability to more accurately represent what is happening.