1

我将使用 shapeless 库作为示例:

import shapeless.test.illTyped

假设我想将illType函数包装在另一个函数中,我尝试了 2 种不同的方法来做到这一点:

(按价值)

  def shouldTypeError(v: String) = illTyped(v, ".*")

[ERROR] ... : exception during macro expansion: 
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
    at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)

(按名字)

  def shouldTypeError(v: => String) = illTyped(v, ".*")

[ERROR ... ]: exception during macro expansion: 
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
    at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)

所以它们都没有按预期工作。这在最新的 scala 或 dotty 中是否可行?

4

1 回答 1

2

不,外部函数也必须是宏

def shouldTypeError(v: String): Unit = macro shouldTypeErrorImpl

def shouldTypeErrorImpl(c: blackbox.Context)(v: c.Tree): c.Tree = {
  import c.universe._
  q"""_root_.shapeless.test.illTyped($v, ".*")"""
}
于 2021-06-20T12:03:45.193 回答