Scala 3宏创建枚举

Scala 3 macro to create enum

我想知道是否可以在 Scala 3 中编写一个宏,它接受一组字符串并将其转换为枚举类型,并以这些字符串作为大小写?

例如,我想编写一个 class,其中包含从输入元素生成的内部类型:

import scala.quoted.*

class Example(myEnumElements:Seq[String]) {
  
  inline def buildEnum(inline elts:Seq[String]): Unit = ${ buildEnumType('elts) }

  def buildEnumType(e: Expr[Seq[String]])(using Quotes, Type[Seq]): Expr[Unit] = '{
    enum MyEnum:
      ???
  }
}
...
// Possibly in another file?

val example = Example(Seq("A","B","C"))

def someConvenienceFunction(e:example.MyEnum) = e match
  case A => "apple"
  case B => "banana"
  case C => "cranberry"
...
// Possibly in another file?

someConvenienceFunction(example.A)  // "apple"
someConvenienceFunction(example.D)  // compile error

Scala 3 宏目前只有 def 宏。它们不是用于生成 类、枚举等。即使您在 buildEnumType 中定义了一个枚举,它也只会在 buildEnum 调用扩展到的块 {...} 中可见。

尝试改用代码生成。

https://users.scala-lang.org/t/macro-annotations-replacement-in-scala-3/7374

How to create variables with macros in Scala(斯卡拉 2)

Resolving variables in scope modified by Scala macro(Scala 2)