This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Declaring a class normally versus in a package object

2 replies
paulbutcher
Joined: 2010-03-08,
User offline. Last seen 10 weeks 5 days ago.

I asked this on StackOverflow without any luck, so I thought I'd try here :-)

http://stackoverflow.com/questions/8696430

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?

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: paul [at] paulbutcher [dot] com
AIM: paulrabutcher
Skype: paulrabutcher

Peter 2
Joined: 2011-02-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Declaring a class normally versus in a package object

Hi Paul,

obviously a package is not the same as its package object hence the
difference in the class file names. On the other side the language
spec states that members of a package object will be added to the
package. That is the reason you can reference them as if they were
directly in that package although they are not.

Does this answer your question?

Peter

paulbutcher
Joined: 2010-03-08,
User offline. Last seen 10 weeks 5 days ago.
Re: Declaring a class normally versus in a package object

On 2 Jan 2012, at 16:04, Sonnenschein wrote:
> obviously a package is not the same as its package object hence the
> difference in the class file names. On the other side the language
> spec states that members of a package object will be added to the
> package. That is the reason you can reference them as if they were
> directly in that package although they are not.

Actually, I'm not sure that that's true - see Jason's answer on SO:

http://stackoverflow.com/questions/8696430/is/8701381#8701381

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: paul [at] paulbutcher [dot] com
AIM: paulrabutcher
Skype: paulrabutcher

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland