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

Accessing the instances of Scala objects from Java code

1 reply
Alex Cruise
Joined: 2008-12-17,
User offline. Last seen 2 years 26 weeks ago.
Hey folks,
I filed http://lampsvn.epfl.ch/trac/scala/ticket/3846 last week and Tiark rightly pointed out that it deserves wider discussion on the list.
To sum up, calling *methods* on Scala objects from Java is easy and idiomatic thanks to the static forwarder methods.  However, when you want to access the *instance* of the object itself, you need to do this ugly dance:
Foo$.MODULE$
My usual workaround is:
object Foo {  def it = this}
So now, in Java, I can just say Foo.it() and everybody's happy--at least as happy as a Scala programmer coding in Java can be. :)
I think a lot of people would benefit if a similar method were generated for us on all Scala objects.  "it" is probably not an ideal name, "instance" might be a reasonable choice, or even "getInstance" if we really want to pander. ;)
TIA for your comments!
-0xe1a
daniel
Joined: 2008-08-20,
User offline. Last seen 44 weeks 14 hours ago.
Re: Accessing the instances of Scala objects from Java code
The problem is that if the compiler were to auto-generate such a method for all objects, there's always the possibility of a name collision.  The only reason MODULE$ doesn't collide is the use of $.

Daniel

On Mon, Sep 20, 2010 at 3:44 PM, Alex Cruise <alex@cluonflux.com> wrote:
Hey folks,
I filed http://lampsvn.epfl.ch/trac/scala/ticket/3846 last week and Tiark rightly pointed out that it deserves wider discussion on the list.
To sum up, calling *methods* on Scala objects from Java is easy and idiomatic thanks to the static forwarder methods.  However, when you want to access the *instance* of the object itself, you need to do this ugly dance:
Foo$.MODULE$
My usual workaround is:
object Foo {  def it = this}
So now, in Java, I can just say Foo.it() and everybody's happy--at least as happy as a Scala programmer coding in Java can be. :)
I think a lot of people would benefit if a similar method were generated for us on all Scala objects.  "it" is probably not an ideal name, "instance" might be a reasonable choice, or even "getInstance" if we really want to pander. ;)
TIA for your comments!
-0xe1a

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