什么是Scala相当于Java的静态块? [英] What is Scala equivalent of Java's static block?

查看:181
本文介绍了什么是Scala相当于Java的静态块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是Scala相当于Java的静态块?

What is Scala equivalent of Java's static block ?

推荐答案

构造函数(即正文)中的代码伴随对象与Java类的静态初始化程序块中的代码完全相同。在下面的示例中,我创建了A的实例,但不会进行初始化。

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!

这篇关于什么是Scala相当于Java的静态块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆