How to pass Scala enum from Java

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

object MonthSelection extends Enumeration {
   type MonthSelection = Value

   val LastMonth, ThisMonth, NextMonth, CustomMonth = Value
}

class MyClass {

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

      

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

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

      

+3


source to share


1 answer


When in doubt, take a 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();
}

      

Okay, easy. All of these enums are public static methods. I just need to import scala.Enumeration and call these methods directly.



$> 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 for playing. :)

+5


source







All Articles