[英]Updatable singleton object in Scala
I would like a singleton object in Scala that has an updatable field. 我想要Scala中具有可更新字段的单例对象。 Is there a better solution than what I have below that doesn't use a
var
? 有没有比下面没有使用
var
更好的解决方案?
class Foo {
def setFoo(newFoo: String): Unit = {
Foo.foo = newFoo
}
def getFoo: String = {
Foo.foo
}
}
object Foo {
var foo = "foo"
}
If you want mutability (ie a variable being constantly updated), var
is your only option. 如果您想要可变性(即变量不断更新),则
var
是唯一的选择。
But you can write it in an "immutable way" in which set
means creating a new immutable instance: 但是您可以用“不可变的方式”编写它,其中
set
意味着创建一个新的不可变的实例:
class Foo(foo: String) {}
object Foo {
create(foo: String): Foo = new Foo(foo)
}
// ...
Foo foo = Foo.create("foo")
val bar = foo.foo // "foo"
I would stick with your original implementation, but shield your mutable singleton to the associated class: 我会坚持使用您的原始实现,但将可变的单例屏蔽到关联的类中:
class Foo {
def setFoo(newFoo: String): Unit = {
Foo.foo = newFoo
}
def getFoo: String = {
Foo.foo
}
}
private [Foo] object Foo {
var foo = "foo"
}
Better solution to what you have that does use var
could be simply 可以使用
var
更好地解决现有问题
object Foo {
var foo = "foo"
}
just this, you don't need the class and those setters, compiler will generate them for you. 只是这样,您不需要类和那些设置器,编译器会为您生成它们。 Now you can just do:
现在您可以执行以下操作:
Foo.foo = "bar"
or read value like this 或像这样读取值
Foo.foo
I don't see a way to have mutable state in object without vars though. 我没有办法在没有变量的情况下在对象中具有可变状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.