Search code examples
javascalaenumerationcase-classscala-option

Instantiate a case class with Options and Scala Enumeration in Java


It seems like if a case class has both enums and options, I cannot instantiate it from Java.

Consider the following in Scala:

object WeekDay extends Enumeration {
    type WeekDay = Value
    val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
  }
case class EnumOption(e: WeekDay.Value, s: Option[String])
case class EnumOnly  (e: WeekDay.Value, s: String)
case class OptionOnly(e: Int, s: Option[String])

And the following in Java to use them:

scala.Enumeration.Value monday = WeekDay.Mon();
EnumOption a = new EnumOption(monday, Option.apply("12"));
EnumOnly b = new EnumOnly(monday, "12");
OptionOnly c = new OptionOnly(12, Option.apply("12"));

I get an error (at least Eclipse shows me an error) on instantiating a but b and c work just fine! Any idea how I can instantiate EnumOption in Java???


Solution

  • EDIT: Now the same code gives me no error. So it was an eclipse bug, and it is not reproducible!


    Disclaimer: This is only a workaround that I have currently opted for.

    case class EnumOption(e: WeekDay.Value, s: Option[String])
    object EnumOption {
      def optionAvailable(e: WeekDay.Value, s: String) = new EnumOption(e, Some(s))
      def notAvailable(e: WeekDay.Value) = new EnumOption(e, None)
    }
    

    and then use either of the two methods above.

    Clearly this is not a viable solution if there are many Options around and the combinations would grow radically. But for my case (the real application) I had three combinations. Of course, I hope there will be a better solution.