1

Let's say I have the following object:

object CaseObjs {
  trait Person
  case object Female extends Person
  case object Male extends Person
}

For purposes of Don't Repeat Yourself, I'd like to use these CaseObjs.Male and .Female as an Enum-like data structure in Java.

In other words, I'd like to use these case object's in Java rather than create a new Java enum that duplicates code.

Can I do this?

Beryllium
  • 12,808
  • 10
  • 56
  • 86
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • possible duplicate of [Custom Scala enum, most elegant version searched](http://stackoverflow.com/questions/20089920/custom-scala-enum-most-elegant-version-searched) – iwein Jul 03 '14 at 19:08
  • Do you know if macros are the only way? I appreciate the reply, but, I know nothing about macros, so implementing a `java enum` for my `Person` trait, per the example above, might be an OK option given my lack of knowledge of Macros. – Kevin Meredith Jul 03 '14 at 20:41
  • I think that in most cases you get away with a sealed trait + case object solution and the macro's are not needed. I think the interop aspect of the question is the most interesting part. – iwein Jul 05 '14 at 07:07
  • After reading a bit more carefully I think it is _the_ option Kevin. The macro solution will not make your Java code look any better as far as I can tell. – iwein Jul 05 '14 at 07:15
  • I wonder what you didn't like about my answer and downvoted it, Kevin :/ You don't need any macro knowledge to use the `Enum`, and you can refer the generated Seq from Java code just like you always do. I can tell you exact what to do with the `Enum` if you need any help with it. – Ryoichiro Oka Jul 05 '14 at 07:42
  • Perhaps you can find a solution that suits you in [that post](http://www.linkedin.com/groups/How-implement-Enums-in-SCALA-746917.S.275804885) – eruve Jul 05 '14 at 10:13
  • hey @RyoichiroOka - I didn't downvote your post. I'll read more of your and `iwein`'s answers later today – Kevin Meredith Jul 05 '14 at 15:39

2 Answers2

0

Short answer: No. See also this question

According to this old post on scala-lang the best way to achieve interoperability is to declare the enum in Java. I haven't found any reason to believe that has changed since then.

Using the different Scala variants will make your Java code look bad, and using Java enums from Scala is straight forward.

Community
  • 1
  • 1
iwein
  • 25,788
  • 10
  • 70
  • 111
-1

You mean you want to index out all children of a sealed class? Then I think this post will help you. Make sure that the implementation assumes that all the children of the class are directly-inheriting case objects. Also scala.Enumeration can be used if those children need not specific implementation.

Community
  • 1
  • 1
Ryoichiro Oka
  • 1,949
  • 2
  • 13
  • 20