I have a constructor defined as
class Test{ var i = 0; println("constructor"); }
And I call it as
val t = new Test { println("codeblock"); i = 7; }
The result of this is:
constructor
codeblock
defined class Test
t: Test = $anon$1@4a7b4f79
res3: Int = 7
So I see that the code block on the same line as new is executed as if it was part of the constructor. I am not familiar with this.
Could some one clarify this behaviour and/or point to reference that explains the semantics at play here? I am not sure how to google this - looking for code block on same line as constructor call scala
doesn'y help much.
It's roughly equivalent to this:
class Test{ var i = 0; println("constructor"); }
class TestImpl extends Test {
println("codeblock")
i = 7
}
scala> new TestImpl
constructor
codeblock
res8: TestImpl = TestImpl@6baf697c
scala> res8.i
res9: Int = 7
So you can see that initialization order comes from more abstract to a more concrete class.
To highlight @som-snytt's comment pointing to Scala Language Specification: general instance creation expression
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.