Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: order of definition for companion object vs case class

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?

like image 986
Gregor Scheidt Avatar asked Dec 21 '11 13:12

Gregor Scheidt


People also ask

Can case class have companion object?

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.

What is difference between Case class and case object in Scala?

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).

What is difference between class and case class in Scala?

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).

What is the advantage of companion object in Scala?

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.


2 Answers

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.

like image 73
Matthew Farwell Avatar answered Oct 01 '22 19:10

Matthew Farwell


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?

like image 28
Daniel C. Sobral Avatar answered Oct 01 '22 19:10

Daniel C. Sobral