我正在尝试通过 Scala 3.0.0-M2 中的宏获取函数名称我想出的解决方案使用TreeAccumulator
import scala.quoted._
inline def getName[T](inline f: T => Any): String = ${getNameImpl('f)}
def getNameImpl[T](f: Expr[T => Any])(using Quotes): Expr[String] = {
import quotes.reflect._
val acc = new TreeAccumulator[String] {
def foldTree(names: String, tree: Tree)(owner: Symbol): String = tree match {
case Select(_, name) => name
case _ => foldOverTree(names, tree)(owner)
}
}
val fieldName = acc.foldTree(null, Term.of(f))(Symbol.spliceOwner)
Expr(fieldName)
}
调用此代码时,会生成函数的名称:
case class B(field1: String)
println(getName[B](_.field1)) // "field1"
我想知道这是否可以使用引号以更简单的方式完成。