What is Scala equivalent of Java's static block?

痞子三分冷 提交于 2019-12-20 11:10:11

问题


What is Scala equivalent of Java's static block ?


回答1:


Code in the constructor (that is, the body) of the companion object is not precisely the same as code in a static initialiser block of a Java class. In the example below, I create an instance of A, but the initialization does not occur.

scala> object Test { class A; object A { println("A.init") }}        
defined module Test

scala> new Test.A
res3: Test.A = Test$A@3b48a8e6

scala> Test.A
A.init
res4: Test.A.type = Test$A$@6e453dd5

To trigger construction of the companion object when the first instance of the class is created, you could access it from the class constructor.

scala> object Test { class A { A }; object A { println("A.init") }}
defined module Test

scala> new Test.A                                                  
A.init
res5: Test.A = Test$A@4e94a28e

scala> new Test.A
res6: Test.A = Test$A@30227d4e

In many circumstances, the difference would not matter. But if you are launching missiles (or other side effects), you might care!



来源:https://stackoverflow.com/questions/2347107/what-is-scala-equivalent-of-javas-static-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!