scala 对象作为字段
可能的重复:
scala 类中的 val 和 object?
之间有本质区别吗 ? :
class Foo {
object timestamp extends java.util.Date
}
拥有一个带有对象字段的类到底
class Foo {
val timestamp = new java.util.Date {}
}
意味着什么?它们有什么用?是否存在必须使用对象的情况?
谢谢...
Possible Duplicate:
val and object inside a scala class?
Is there a substantive difference between:
class Foo {
object timestamp extends java.util.Date
}
and
class Foo {
val timestamp = new java.util.Date {}
}
What does it really mean to have a class with an object field? What are they used for? Are there situations where you must use an object?
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要向字段添加行为,那么使用
对象
可能会更好。例如:foo.startDate
的类型是foo.startDate.type
,调用foo.startDate.isBusinessDay
方法将是静态解析。另一方面,
bar.startDate
的类型是结构类型java.util.Date{ def isBusinessDay: Boolean }
。因此,调用bar.startDate.isBusinessDay
将使用反射并产生不必要的运行时开销。Using an
object
may be preferable if you need to add behavior to the field. For example:The type of
foo.startDate
isfoo.startDate.type
, and a call to thefoo.startDate.isBusinessDay
method will be resolved statically.The type of
bar.startDate
, on the other hand, is the structural typejava.util.Date{ def isBusinessDay: Boolean }
. A call tobar.startDate.isBusinessDay
will therefore use reflection and incur unnecessary runtime overhead.有两个区别,一是重要的,一是微妙的。首先,对象是延迟启动的。出于您的目的,这意味着您的第二个示例应该是
让它们表现相同。更巧妙的是,每个对象都有自己独特的类型。在您的示例中,
timestamp
将具有类型Foo.timestamp.type
。这在实践中通常并不重要,但如果您以反射方式访问对象,则可能会导致意外。Two differences, one important, one subtle. First, objects are lazily initiated. For your purposes, this means your second example should be
for them to behave equivalently. More subtly, each object has it's own unique type. In the case of your example,
timestamp
will have typeFoo.timestamp.type
. This normally isn't important in practice, but may cause surprises if you are accessing objects reflectively.它们的行为方式基本相同。我曾假设
class X { object Y ... }
只会为XY
提供一个命名空间。我使用Y
来存储与X
相关的(常量)实用程序数据,具体是因为我期望有一个唯一的XY
。事实上,我在进行内存分析时发现的每一个新X
都会构造一个新对象。Those do behave basically the same way. I had assumed that
class X { object Y ... }
would simply provide a namespace forX.Y
. I usedY
to store (constant) utility data related toX
specifically because I expected one uniqueX.Y
. In fact, one new object was constructed for every newX
which I discovered when doing memory profiling.