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?
When you want to define some functionality related to a case class you have two possible ways to do this. The first one is to create functions directly in the case class. Note that in order to define a companion object for a class you have to set the same names for them and declare them in the same file.
A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).
A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).
Advantages of Companion Objects in Scala Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class's runtime objects but is available from a static context and vice versa.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With