Scala 构造函数
Scala 中的以下 Java 代码相当于什么:
import java.util.Random;
public class Bool {
private boolean door;
Random random = new Random();
Bool() {
this.door = random.nextBoolean();
}
}
因此,当创建一个新的 Bool 对象时,door 变量将自动获取一个随机布尔值。
What is the equivalent of the below Java code in Scala:
import java.util.Random;
public class Bool {
private boolean door;
Random random = new Random();
Bool() {
this.door = random.nextBoolean();
}
}
So when a new Bool object is created, the door variable will automatically get a random Boolean value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Scala 中,类的主体相当于 Java 中构造函数调用的方法。因此,您的类将如下所示:(
请注意,要挑剔,因为您没有声明 Java 变量
final
,有人可能会认为字段应该是varrandom
字段是受包保护的,这看起来像是一个疏忽,并且会在 Scala 中呈现为protected[pkgName]
其中pkgName
是类包中最具体组件的名称。)In Scala, the body of the class is equivalent to the methods invoked by a constructor in Java. Hence your class would look something like the following:
(note that to be picky, since you didn't declare your Java variables
final
, one could argue that the fields should bevar
s here instead. Additionally, yourrandom
field is package-protected which looks like an oversight, and would be rendered in Scala asprotected[pkgName]
wherepkgName
is the name of the most specific component of the class' package.)这是我的看法:
这使得创建具有特定门值的
MyBool
新实例成为可能,例如:由于只能有两个不同的门值,因此使用静态对象是有意义的相反,像这样:
用法:
Here is my take:
This leaves open the possibility to create a new instance of
MyBool
with a certain door value, e.g.:Since there can only be two different door values, it would make sense to use static objects instead, like this:
Usage:
更接近的 scala 代码应该是:
即使公共随机字段看起来不是一个好主意。
The closer scala code should be:
Even if the public
random
field does not look as a good idea.