1

I am converting the following code in C++ to Scala :

enum Value{ a = 0 , b = 0 , c = 12 , d = 13}

and I have implemented in following way :

object Value extends Enumeration {
 val a = Value(0) 
 val b = Value(0) 
 val c = Value(12) 
 val d = Value(13) 
}

but it displays an error when I called Value(0).id reporting

java.lang.AssertionError: assertion failed: Duplicate id: 0

How to assign duplicate values ?

j0k
  • 22,600
  • 28
  • 79
  • 90
  • Did you forgot about `type Value` ref: http://stackoverflow.com/questions/1321745/scala-doesnt-have-enums-what-to-use-instead-of-an-enum – Lukasz Madon May 22 '13 at 09:23
  • still , it's not working : `object Value_id extends Enumeration {type value_id = Value val a = Value(0) val b = Value(0) val c = Value(12) val d = Value(13) }` –  May 22 '13 at 09:31

2 Answers2

2

You could do this:

object Value extends Enumeration {
  val a = Value(0)
  val b = a
  val c = Value(12)
  val d = Value(13)
}
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • hey thanks ! but when we call Value(0) , it gives b and not a ? why is this and how to get both of a and b in form of set by calling Value(0) –  May 22 '13 at 09:38
  • You cannot get both of them. Those IDs are supposed to be unique anyway; this would be a curious hack to get two "enum values" to refer to the same ID, which is probably not advisable anyway… – Jean-Philippe Pellet May 22 '13 at 09:45
  • 2
    I think `Enumeration` isn't a good choice for what you are trying to achieve. Probably a `Map` or `List` (some collection) will be better choice.. – Shrey May 22 '13 at 09:53
  • and how to use enum Months{Jan , Feb , March , ....Dec = 12} in Scala ? if we use object Months extends Enumeration{val Jan, Feb, March , ...., Dec = Value(12)} , it would assign duplicate id's. Any suggestions please ? –  May 22 '13 at 12:52
  • Where's the problem? Make a separate call to `Value()` for each enum value. – Jean-Philippe Pellet May 22 '13 at 13:42
  • what other Value() function you are suggesting ? –  May 22 '13 at 13:57
0

The problem is that you got 2 definitions of value 0, if you want that you can do:

object EnumValue extends Enumeration {
   type EnumValue = Value
   val a = Value(0)
   val b = a
   val c = Value(12)
   val d = Value(13)
}

 println(EnumValue.a.toString) 
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108