什么取代了 Scala 中的类变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1888716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What replaces class variables in scala?
提问by paradigmatic
In Java I sometimes use class variables to assign a unique ID to each new instance. I do something like
在 Java 中,我有时使用类变量为每个新实例分配一个唯一的 ID。我做类似的事情
public class Foo {
private static long nextId = 0;
public final long id;
public Foo() {
id = nextId;
nextId++;
}
[...]
}
How can I do this in Scala?
我怎样才能在 Scala 中做到这一点?
回答by Thomas Jung
Variables on the companion object:
伴随对象上的变量:
object Foo{
private var current = 0
private def inc = {current += 1; current}
}
class Foo{
val i = Foo.inc
println(i)
}
回答by Carl Smotricz
To amplify on Thomas' answer:
放大托马斯的回答:
The objectdefinition is usually put in the same file with the class, and musthave the same name. This results in a single instance of an object having the name of the class, which contains whatever fields you define for it.
该object定义通常被放在与类相同的文件,并且必须具有相同的名称。这会产生一个具有类名称的对象的单个实例,其中包含您为它定义的任何字段。
A handy do-it-yourself Singleton construction kit, in other words.
换句话说,这是一个方便的自己动手做的 Singleton 构建套件。
At the JVM level, the object definition actually results in the definition of a new class; I think it's the same name with a $appended, e.g. Foo$. Just in case you have to interoperate some of this stuff with Java.
在JVM层面,对象定义实际上导致了一个新类的定义;我认为它与$附加的名称相同,例如Foo$. 以防万一您必须与 Java 互操作这些东西。

