views:

466

answers:

3
object TestEnum extends Enumeration{
  val One = Value("One")
  val Two,Three= Value
}
println(TestEnum.One.getClass)
println(TestEnum.One.getClass.getDeclaringClass)//get Enumeration

So my question is how to get Class[TestEnum] from TestEnum.One?

Thanks.

+4  A: 

I don't think you can unfortunately. TestEnum.One is really just an instance of the class Enumeration#Value. In fact, it's lots worse than just this - your enumeration values are all erased by type to the same thing:

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

def foo(w: Weekday.Value)
def foo(e: TestEnum.Value) //won't compile as they erase to same type

As the instances of your enumeration are just instances of Enumeration#Value, their declaring class is just scala.Enumeration.

It's frustrating but it seems like these scala enums are worse than useless; if you pass them through serialization (at least in 2.7.7), then you can't do equality checks either!

oxbow_lakes
Indeed,the scala default enum is awful,but it near to java enum,you can save your writing for simple enums :)
Ford Guo
+1  A: 

I am going to post a link to the Enum type that I wrote due to the limitations you mentioned. I don't use the built in enumeration type as I find it very limiting. Though it doesn't have the feature you would like (get the Enumeration from an Element), it would be pretty trivial to add it. Feel free to use it in any way if you find it helpful.

(source & test / example): http://gist.github.com/282446

BTW If you like and want help adding the container to the EnumElement let me know.

King Cub
It's a good idea,and is there any way to reduce the writing codes?,Like scala enum,
Ford Guo
not that i can think of this has a lot more power than the scala enumeration though, so it's a trade-off. The scala enum doesn't have a to string on its elements (unless you say Mon("Mon") ...), which is a common use case.
King Cub
A: 

In my opinion there is a simple solution for not dealing with Scala Enumerations: use Java enum-s instead. Scala has supported cross-compiling for a while now and it's easy to just add a Java enum in your Scala source folder.

Erkki Lindpere
Sound good,I will make the choice,Thanks Erkki
Ford Guo