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.
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 Enumeration
s posessed, Scala 2.8's Enumeration
s certainly possess everything you're looking for.
You can't define values with object SUNDAY extends Value(1)
because object
s are initialized lazily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With