Paul Butcher
Paul Butcher

Reputation: 10852

Is there any substantive difference between declaring a class normally versus in a package object?

If I have a package com.example, I can create a class in that package like this:

package com.example {
  class MyClass
}

or like this:

package com {
  package object example {
    class MyClass
  }
}

In both cases, the resulting class is (as far as other Scala code is concerned, at least) com.example.MyClass.

There are certainly incidental differences. In the first instance, the resulting compiled class is com/example/MyClass.class whereas in the second it's com/example/package$MyClass.class but are there any substantive differences?

Upvotes: 7

Views: 287

Answers (2)

retronym
retronym

Reputation: 55028

The difference in generated class file names was discussed on scala-internals, and hopefully will disappear in Scala 2.10.

Upvotes: 5

agilesteel
agilesteel

Reputation: 16859

The only reason I can think of is that instead of being able to put only classes, objects or types in a package, you can put defs, vals and vars in an object.

Upvotes: 0

Related Questions