2

I am trying to implement a Rich enumeration in Scala, where my enumeration would also have to implement for example a trait.

This work fine, however when I tried to iterate the enumerations, the Enumeration.values returns a ValueSet, which is a collection of Enumeration.Value

Is there a simple way to implement this feature, without going to macros and sealed traits are suggested from Travis Brown Iteration over a sealed trait in Scala? ?

Community
  • 1
  • 1
Edmondo
  • 19,559
  • 13
  • 62
  • 115

3 Answers3

3

Enumeration in scala can be done relatively easy with an Enumeration class. Below is an example of it.

trait Num {
  def echo
}

object Status extends Enumeration {

  case class StatusVal(code: Int, name: String) extends Val with Num {
    override def echo {
      println("Number: " + name)
    }
  }
  val ONE = StatusVal(1, "One")
  val TWO = StatusVal(2, "Two")
  val THREE = StatusVal(2, "Three")
}

Status.values foreach (s => s.asInstanceOf[Num].echo)
kikulikov
  • 2,512
  • 4
  • 29
  • 45
1

Have you tried implicit conversions? Remember to keep the scope tight:

// I have deliberated stolen @cyrillk example :). 
// Just add this line to the body os Status (Enumeration Object)
implicit def valueToNum(v: Value): Num = v.asInstanceOf[Num]

Value will be implicit cast to Num, so:

Status.values foreach (s => s.echo) // works!

Working Example


Chek out a Better example by Sean Ross.

Community
  • 1
  • 1
Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
1

You may have to convert first:

Enumeration and mapping with Scala 2.10

I guess both answers there are relevant, but I'd totally forgotten mine.

This thread

https://groups.google.com/d/msg/scala-internals/8RWkccSRBxQ/snNuzjJakhkJ

might mark the start of the long road to the enum replacement. It contains a few divergent (pun alert) opinions on usage.

Early stop on the road:

https://stackoverflow.com/a/4346618/1296806

Community
  • 1
  • 1
som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • I think the last link says it correctly: "Honestly, I wouldn't use Enumeration. This is a class originating from Scala 1.0 (2004) " – Edmondo Feb 17 '14 at 07:49