简体   繁体   English

在 Scala 中创建新对象后的代码块

[英]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.所以我看到与 new 同一行的代码块被执行,就好像它是构造函数的一部分一样。 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.我不知道如何用谷歌搜索这个 - 在code block on same line as constructor call scala寻找code block on same line as constructor call scala多大帮助。

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突出显示指向 Scala 语言规范的@som-snytt 注释: 通用实例创建表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM