I'm kind like discovering the macros for an use case in which I tried to extract the lambda arg names from a function. To do so, I've defined this class (let's say in a module A):
object MacroTest {
def getLambdaArgNames[A, B](f: A => B): String = macro getLambdaArgNamesImpl[A, B]
def getLambdaArgNamesImpl[A, B](c: Context)(f: c.Expr[A => B]): c.Expr[String] = {
import c.universe._
val Function(args, body) = f.tree
val names = args.map(_.name)
val argNames = names.mkString(", ")
val constant = Literal(Constant(argNames))
c.Expr[String](q"$constant")
}
Now in another module, I'm trying to write an unit like to check the names of the argument named passed to a lambda :
class TestSomething extends AnyFreeSpec with Matchers {
"test" in {
val f = (e1: Expr[Int]) => e1 === 3
val argNames = MacroTest.getLambdaArgNames(f)
println(argNames)
assert(argNames === "e1")
}
}
But this code doesn't compile because of :
scala.MatchError: f (of class scala.reflect.internal.Trees$Ident)
But if I pass directly the lambda to the function like MacroTest.getLambdaArgNames((e1: Expr[Int]) => e1 === 3)
it's working so I'm pretty lost about the reason that makes the code not compiling.
Any possible solution to fix that ?