Scala: order of definition for companion object vs case class
Asked Answered
S

2

20

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?

Salpinx answered 21/12, 2011 at 13:37 Comment(0)
B
14

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.

Benedix answered 21/12, 2011 at 14:35 Comment(1)
It is pretty easy to work around, so I'm not sure it is worth voting up. Thanks for the link to the ticket.Salpinx
M
1

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?

Management answered 21/12, 2011 at 15:10 Comment(2)
Wait, what? :-) Did you mean "classes and objects can have forward definitions, but methods cannot"?Salpinx
@GregorScheidt Neither methods nor functions. Well, Scala Spec don't know what a "method" is, so I might as well call them functions, but I hate the name confusion around "function".Management

© 2022 - 2024 — McMap. All rights reserved.