Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala enumerations with Singleton objects as enumeration elements and a possibility to iterate over them?

I already looked at the Scala question about emulating Java's enum and case classes vs. Enumeration but It seems too much effort for too less benefit.

Basically I would like to have a values method returning all singleton objects of DayOfWeek without repeating myself a few times.

This is how my code should look like:

object DayOfWeek extends MyEnum {
  object MONDAY extends DayOfWeek(1)
  object TUESDAY extends DayOfWeek(2)
  object WEDNESDAY extends DayOfWeek(3)
  object THURSDAY extends DayOfWeek(4)
  object FRIDAY extends DayOfWeek(5)
  object SATURDAY extends DayOfWeek(6)
  object SUNDAY extends DayOfWeek(7)
}

class DayOfWeek(ordinal: Int)

The method values should return something like if it had been written like this:

val values = Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
                   FRIDAY, SATURDAY, SUNDAY)

Everything should happen in the MyEnum trait so I only need to extend it to get the functionality.

trait MyEnum {
  val values = this.getClass.getField("MODULE$") etc. etc.
}

Any suggestion how this could be done exactly? The idea is that values accesses the class and finds all singleton objects of the class they are extending.

Edit: It looks like all suggestions don't take in account that the user can create objects too which should of course be comparable to the defined ones.

I'll try to give another example, maybe it is more clear:

object MonthDay extends MyEnum {
  //Some important holidays
  object NewYear       extends MonthDay( 1,  1)
  object UnityDay      extends MonthDay(11,  9)
  object SaintNicholas extends MonthDay(12,  6)
  object Christmas     extends MonthDay(12, 24)
}

class MonthDay(month: Int, day: Int)

//Of course the user can create other MonthDays
val myBirthDay = new MonthDay(month, day)

if(!MonthDay.values.contains(myBirthDay)) "Well, I probably have to work"
else "Great, it is a holiday!"

I want to have a trait (MyEnum) which I can mix into the object holding my "enumeration objects" with methods to return a list of them (def values: List[MonthDay]) or iterate over them (def next: MonthDay or def previous: MonthDay).

PPS: I created a new question for the second part of this question as requested by Ken Bloom.

like image 296
soc Avatar asked Nov 20 '10 22:11

soc


1 Answers

scala.Enumeration does exactly what you want already.

I think you may be confused by Scala 2.7 versus Scala 2.8. The old question you cite about emulating Java's enum was written in the days of Scala 2.7, and though I can't go test what functionality Scala 2.7's Enumerations posessed, Scala 2.8's Enumerations certainly possess everything you're looking for.

You can't define values with object SUNDAY extends Value(1) because objects are initialized lazily.

like image 190
Ken Bloom Avatar answered Nov 15 '22 17:11

Ken Bloom