Scala 相当于 Java 的 static 块吗?

发布于 2024-08-23 07:59:37 字数 34 浏览 1 评论 0原文

Scala 相当于 Java 的 static 块吗?

What is Scala equivalent of Java's static block ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

披肩女神 2024-08-30 07:59:37

伴生对象的构造函数(即主体)中的代码与 Java 类的静态初始化块中的代码完全相同。在下面的示例中,我创建了 A 的实例,但未进行初始化。

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

要在创建类的第一个实例时触发伴随对象的构造,您可以从类构造函数访问它。

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

在许多情况下,差异并不重要。但如果您正在发射导弹(或其他副作用),您可能会关心!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文