我有一个构造函数,定义为
class Test{ var i = 0; println("constructor"); }我把它叫做
val t = new Test { println("codeblock"); i = 7; }这样做的结果是:
constructor
codeblock
defined class Test
t: Test = $anon$1@4a7b4f79
res3: Int = 7所以我看到与new在同一行上的代码块被执行,就像它是构造函数的一部分一样。我对此并不熟悉。
有人可以澄清这种行为和/或引用来解释这里起作用的语义吗?我不知道怎么用谷歌搜索这个--搜索code block on same line as constructor call scala帮不了多少忙。
发布于 2017-01-21 14:36:52
它大致相当于:
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因此,您可以看到,初始化顺序从更抽象的类到更具体的类。
要突出显示@som-snytt指向Scala语言规范的评论:general instance creation expression
https://stackoverflow.com/questions/41776392
复制相似问题