Scala:伴生对象与案例类的定义顺序
在 Scala 2.9.1 中,我得到以下行为:
class Foo {
case class X()
object X // this compiles
def bar() {
object Y // this compiles
case class Y()
case class Z()
object Z // won't compile (see below)
}
}
编译器抱怨 Object Z
: 错误:Z 已定义为(编译器生成的)案例类伴随对象 Z
看起来好像不允许在案例类定义之后为案例类定义伴随对象(如果它们位于函数定义内)。这是编译器错误还是故意的?如果是后者,为什么?
In Scala 2.9.1 I get the following behavior:
class Foo {
case class X()
object X // this compiles
def bar() {
object Y // this compiles
case class Y()
case class Z()
object Z // won't compile (see below)
}
}
The compiler complains for Object Z
:
error: Z is already defined as (compiler-generated) case class companion object Z
It looks as if it is not permissible to define a companion object for a case class after the case class definition if they are within a function definition. Is this a compiler bug, or intentional? If the latter, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个已知错误:SI-3772:同伴和方法拥有的案例类。这已部分解决,但 OP 的问题仍然存在。如果您想修复它,请投票。
This is a known bug: SI-3772: companions and method-owned case classes. This is partially fixed, but the OP's issue still remains. Vote it up if you want it fixed.
之所以允许第一个而第二个不允许,是因为类和对象可以有前向定义,但定义不能。那么为什么编译器可以将
object X
与case类定义的对象混合,在第二种情况下不可能这样做。我想知道在
Y
情况下会发生什么:阴影或对象同伴根本没有生成?The reason why the first is allowed and the second is not is that classes and objects can have forward definitions, but definitions cannot. So why it is possible for the compiler to mix
object X
with the one defined by the case class, it is not possible to do so in the second case.I wonder what happens in the
Y
case: shadowing or the object companion does not get generated at all?