3

I have a Scala/Java dual language project where I need to pass a Scala enumeration from Java.

object MonthSelection extends Enumeration {
   type MonthSelection = Value

   val LastMonth, ThisMonth, NextMonth, CustomMonth = Value
}

class MyClass {

   def doDateStuff(monthChosen: MonthSelection) = {
   // do stuff
   }
}

How do I call this from Java? I am getting a compile error as I cannot seem to import scala.Enumeration.Value.

   MyClass myClass = new MyClass();
   myClass.doStuff(MonthSelection.ThisMonth);

1 Answer 1

5

When in doubt, look at the generated bytecode. :)

$> cat foo.scala
object MonthSelection extends Enumeration {
    type MonthSelection = Value

    val LastMonth, ThisMonth, NextMonth, CustomMonth = Value
}

$> scalac -d bin foo.scala
$> ls bin
MonthSelection$.class  MonthSelection.class
$> javap bin/MonthSelection
Compiled from "foo.scala"
public final class MonthSelection extends java.lang.Object{
    public static final scala.Enumeration$Value CustomMonth();
    public static final scala.Enumeration$Value NextMonth();
    public static final scala.Enumeration$Value ThisMonth();
    public static final scala.Enumeration$Value LastMonth();
    public static final scala.Enumeration$ValueSet$ ValueSet();
    public static final scala.Enumeration$Value withName(java.lang.String);
    public static final scala.Enumeration$Value apply(int);
    public static final int maxId();
    public static final scala.Enumeration$ValueSet values();
    public static final java.lang.String toString();
}

Ok, easy. All of these enumerations are public static methods. I just have to import scala.Enumeration and directly invoke these methods.

$> cat Some.java
import scala.Enumeration;

public class Some {
    public static void main(String args[]) {
        System.out.println("Hello!");
        System.out.println(MonthSelection.CustomMonth());
    }
}

$> javac -cp $SCALA_HOME/lib/scala-library.jar:bin/ -d bin Some.java
$> ls bin
MonthSelection$.class  MonthSelection.class  Some.class
$> java -cp $SCALA_HOME/lib/scala-library.jar:bin Some              
Hello!
CustomMonth

Hope this gives you more ideas to play with. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.