Trait 内的 Scala 对象
在 Scala 中,对象是单例...所以如果我做:
trait SimpleTrait {
def setString(s: String): Unit = {
InnerTraitObject setString s
}
def getString(): String = {
return InnerTraitObject getString
}
object InnerTraitObject {
var str: String = ""
def setString(s: String): Unit = {
str = s
}
def getString(): String = {
return str
}
}
}
然后
class SimpleClass extends SimpleTrait{
/// empty impl
}
和:
object App {
def main(args: Array[String]): Unit = {
val a = new SimpleClass();
val b = new SimpleClass();
a.setString("a");
println("A value is " + a.getString());
println("B value is " + b.getString());
}
}
我想看看,
A value is a
B value is a
但我得到了
A value is a
B value is
我的问题是: 如果对象是单例的,那么为什么如果我将它放入 Trait 中,那么它的行为就像普通对象一样?
In Scala Objects are singletons... so if I make:
trait SimpleTrait {
def setString(s: String): Unit = {
InnerTraitObject setString s
}
def getString(): String = {
return InnerTraitObject getString
}
object InnerTraitObject {
var str: String = ""
def setString(s: String): Unit = {
str = s
}
def getString(): String = {
return str
}
}
}
Then
class SimpleClass extends SimpleTrait{
/// empty impl
}
and:
object App {
def main(args: Array[String]): Unit = {
val a = new SimpleClass();
val b = new SimpleClass();
a.setString("a");
println("A value is " + a.getString());
println("B value is " + b.getString());
}
}
I would like to see
A value is a
B value is a
but i got
A value is a
B value is
My question is:
If object is singleton then why if i put it into Trait then it behave like common object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不是全局单例,而是指特征实例(可以有多个实例)的单例。这取决于您定义单例的位置:如果在包中定义,那么它是与包有关的单例,并且包也是单例,因此对象也是单例。你看,这取决于你将某些东西定义为单例的上下文。如果上下文是单例的,那么定义的对象也是单例的。
It´s not a global singleton, it´s a singleton referring to the instance of the trait (which can have several instances). It depends where you define the singleton: if defined in a package then it´s singleton concerning the package and the package is singleton, too, so the object is singleton. You see, it depends on the context you are defining something as a singleton. If the context is singleton then the defined object too.