小编Yev*_*nyk的帖子

Scala 3 (Dotty) 模式匹配带有宏引用的函数

我正在尝试通过 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)
}
Run Code Online (Sandbox Code Playgroud)

调用此代码时会生成函数的名称:

case class B(field1: String)
println(getName[B](_.field1)) // "field1"
Run Code Online (Sandbox Code Playgroud)

我想知道这是否可以使用引号以更简单的方式完成。

macros scala dotty scala-macros scala-3

8
推荐指数
1
解决办法
290
查看次数

标签 统计

dotty ×1

macros ×1

scala ×1

scala-3 ×1

scala-macros ×1