Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code block following creation of new object in scala

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.

like image 820
divbyzero Avatar asked Oct 17 '25 15:10

divbyzero


1 Answers

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

like image 72
dk14 Avatar answered Oct 20 '25 07:10

dk14



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!