简体   繁体   English

Scala:伴随对象与案例类的定义顺序

[英]Scala: order of definition for companion object vs case class

In Scala 2.9.1 I get the following behavior: 在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)
   }
}

The compiler complains for Object Z : error: Z is already defined as (compiler-generated) case class companion object Z 编译器抱怨Object Z :错误:Z已经被定义为(编译器生成的)案例类伴随对象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? 如果是后者,为什么?

This is a known bug: SI-3772: companions and method-owned case classes . 这是一个已知的错误: SI-3772:随播和方法拥有的案例类 This is partially fixed, but the OP's issue still remains. 这部分是固定的,但OP的问题仍然存在。 Vote it up if you want it fixed. 如果你想修复它,请投票。

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. 那么为什么编译器可以将object X与case类定义的object X混合,在第二种情况下不可能这样做。

I wonder what happens in the Y case: shadowing or the object companion does not get generated at all? 我想知道在Y情况下会发生什么:阴影或对象伴侣根本没有生成?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM