Your confusion results from a misunderstanding of how constructors in Scala works. Specifically, let's translate the Scala code you posted into Java:
class A(val g:String) {
x += g.length
var x:Int = 0
}
becomes
public class A {
public A(String g) {
x += g.length();
x = 0;
}
private int x;
}
The reason is simple. The whole body of a class in Scala is the primary constructor for that class. That means the statements in it, and initializing val
and var
are statements, will be executed in the order they are found.
PS: Here is the actual, true rendition of that code.
Scala 2.7
C:\Users\Daniel\Documents\Scala\Programas> scalac -print A.scala
[[syntax trees at end of cleanup]]// Scala source: A.scala
package <empty> {
class A extends java.lang.Object with ScalaObject {
@remote def $tag(): Int = scala.ScalaObject$class.$tag(A.this);
<paramaccessor> private[this] val g: java.lang.String = _;
<stable> <accessor> <paramaccessor> def g(): java.lang.String = A.this.g;
private[this] var x: Int = _;
<accessor> def x(): Int = A.this.x;
<accessor> def x_=(x$1: Int): Unit = A.this.x = x$1;
def this(g: java.lang.String): A = {
A.this.g = g;
A.super.this();
A.this.x_=(A.this.x().+(g.length()));
A.this.x = 0;
()
}
}
}
Scala 2.8
C:\Users\Daniel\Documents\Scala\Programas>scalac -print A.scala
[[syntax trees at end of cleanup]]// Scala source: A.scala
package <empty> {
class A extends java.lang.Object with ScalaObject {
<paramaccessor> private[this] val g: java.lang.String = _;
<stable> <accessor> <paramaccessor> def g(): java.lang.String = A.this.g;
private[this] var x: Int = _;
<accessor> def x(): Int = A.this.x;
<accessor> def x_=(x$1: Int): Unit = A.this.x = x$1;
def this(g: java.lang.String): A = {
A.this.g = g;
A.super.this();
A.this.x_=(A.this.x().+(g.length()));
A.this.x = 0;
()
}
}
}