scalascalameta

scala-meta: parse vararg in class constructor


How can I parse a Term as shown below and extract the arguments parsed to the class apply method. The class apply method takes a variable argument and hence it is not known how many arguments are present in the class constructor.

q"""TestClass(TestArg(1,2,"c"), TestArg(10,2,"c"))"""

I need to parse and extract the two arguments (the number will change at runtime) passed to the TestClass apply method which takes variable number of arguments (vararg)


Solution

  • You can use the dot-dot unquoting syntax to get a Seq[Tree] containing the arguments, then unpack each of them separately (for example, in a map call).

    val q"TestClass(..$args)" = ???
    val result = args.map { case q"""TestArg($a, 2, "c")""" => ??? }