How to use macros for short, safe types, unboxed enum?

I study Scala macros and see this as an exercise.

Is it possible to use Scala macros to write something like this (maybe not exactly this particular syntax, but something without a template)

enum DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday

And you have a macro extension 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, it may not be necessary to use consecutive integers to represent enumerations. For example, with some flag, we can have enumerations containing no more than 32 or 64 alternatives, like bits, and have an effective unboxed implementation of our set (like Intor Long).

- - enum, , , enum, next Sunday.

+4
2

, Rex Kerr answer, , StaticAnnotation, . Java, .

( ^^)

+1

(Alois Cochard Simon Ochsenreither) , Java, IIRC Scala - -, . , , .

, . , , , , , - (scala meta, ), .

+3

All Articles