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

how to get case object inside a companion object from Java

4 replies
andrey
Joined: 2010-02-16,
User offline. Last seen 1 year 32 weeks ago.
Hi all,I would like to get ADDED in Java:
sealed abstract class QStatus(val char: Char)object QStatus {  case object ADDED extends QStatus('A')  ...}
This solution does not work:
QStatus$.ADDED$.MODULE$

I have seen a similar case on StackOverflow but it does not have a companion object:http://stackoverflow.com/questions/2561415/how-do-i-get-a-scala-case-object-from-java

-Andrey 
H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: how to get case object inside a companion object from Java

you can avoid the nasty stuff by adding a simple getter to the outer object

-------- Original-Nachricht --------
> Datum: Thu, 26 Jan 2012 03:34:16 -0800 (PST)
> Von: Andrey Somov
> An: scala-user [at] googlegroups [dot] com
> Betreff: [scala-user] how to get case object inside a companion object from Java

> Hi all,
> I would like to get ADDED in Java:
>
> sealed abstract class QStatus(val char: Char)
> object QStatus {
> case object ADDED extends QStatus('A')
> ...
> }
>
> This solution does not work:
>
> QStatus$.ADDED$.MODULE$
>
> I have seen a similar case on StackOverflow but it does not have a
> companion object:
> http://stackoverflow.com/questions/2561415/how-do-i-get-a-scala-case-obj...
>
> -
> Andrey
>

andrey
Joined: 2010-02-16,
User offline. Last seen 1 year 32 weeks ago.
Re: how to get case object inside a companion object from Java
I did not quite catch the message. This is how I implemented 'enum' in Scala. In Scala it looks convenient: QStatus.ADDEDNow I need to work in the similar way in Java.
-Andrey
andrey
Joined: 2010-02-16,
User offline. Last seen 1 year 32 weeks ago.
Re: how to get case object inside a companion object from Java
I found the solution:
fullpackage.QStatus$ADDED$.MODULE$
Unfortunately, the package name is required because the Java tool (Eclipse) is confused with such an import statement:
import org.quartzsource.meutrino.facade.QStatus$ADDED$;

It is not beautiful, but it works.-Andrey
geoff
Joined: 2008-08-20,
User offline. Last seen 1 year 25 weeks ago.
Re: how to get case object inside a companion object from Java

With a little indirection you can get something which might be
acceptable:

sealed abstract class QStatus(val char: Char)
object QStatus {
object enums {
case object ADDED extends QStatus('A')
}
val ADDED = enums.ADDED
}

Pattern matching will still work from scala and the java interface is

public abstract class QStatus extends java.lang.Object implements
scala.ScalaObject{
public static QStatus$enums$ADDED$ ADDED();
public char char();
public QStatus(char);
}

so java users can write QStatus.ADDED()

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