I am learning Scala macros and thinking of this as an exercise.
Is it possible to use Scala macros to write down something like this (maybe not exactly this concrete syntax, but something without boilerplate)
enum DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
And have it macro-expand to something like this?
class DayOfWeek private (val ord: Int) extends AnyVal {
def next: DayOfWeek = ord match {
case 0 => Tuesday
case 1 => Wednesday
case 2 => Thursday
case 3 => Friday
case 4 => Saturday
case 5 => Sunday
case _ => throw Error("Sunday does not have next")
}
override def toString: String = ord match {
case 0 => "Monday"
case 1 => "Tuesday"
case 2 => "Wednesday"
case 3 => "Thursday"
case 4 => "Friday"
case 5 => "Saturday"
case _ => "Sunday"
}
}
object DayOfWeek {
def count = 7
val Monday = new DayOfWeek(0)
val Tuesday = new DayOfWeek(1)
val Wednesday = new DayOfWeek(2)
val Thursday = new DayOfWeek(3)
val Friday = new DayOfWeek(4)
val Saturday = new DayOfWeek(5)
val Sunday = new DayOfWeek(6)
}
And maybe not neccessarily using consecutive integers to represent enumerations. For example, with some flag, we can have enums with no more than 32 or 64 alternatives be represented as bits, and have an efficient unboxed implementation of its set (as Int
or Long
).
Another compelling reason for having something like this is we can also customize different aspects for slightly different flavors of enum
, for example, above, we could have provided some parameter to enum
so that next
cycles around instead of erroring on Sunday
.