3

I have a scala Enumeration like this.

object WeekDay extends Enumeration {
    type WeekDay = Value
    val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
  }

How can I use the class in Java?

public WeekDay getWeekDay() {
  return WeekDay.withName(this.myWeekDay);
}

It throws an error:

[error]   required: WeekDay
[error]   found:    Enumeration.Value

1 Answer 1

2

As the error tells you, the type of a Scala's Enumeration members' is actually Value. So:

import scala.Enumeration.Value;
//...
public Value getWeekDay() {
      return WeekDay.withName(this.myWeekDay);
}

Unfortunately, Scala type aliases are not visible from Java code, so you can't use your WeekDay.WeekDay here.

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

6 Comments

It doesn't work. I got this error in the import statement. class Enumeration exists, but it has no companion object.
@angelokh : works fine for me. The error you're getting is typical to Scala (Java has no notion of "companion objects") and indeed appears when you place the import in Scala code. You only need this import in your Java code (Enumeration is in Scala's standard library and hence is auto-imported).
Thank you! But I still get the error. MyInfo.java:15: object Enumeration is not a member of package scala Note: class Enumeration exists, but it has no companion object. This is in java code.
My play version is 2.2 so scala version is 2.10.2.
@angelokh : one more thing - out of curiosity I've decided to try it myself and I got the same error. However, if you put both Java and Scala files into a package (e.g. blah) and the appropriate package folder (e.g. app/blah), the compiler works as it should - both in Scala and Java projects. I suggest you ask a new question about why this is the case, since there's obviously something missing in the Play docs.
|

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.