当然可以——例如:
import scala.language.experimental.macros
import scala.reflect.macros.Context
object Demo {
def at(xs: Any*)(i: Int) = macro at_impl
def at_impl(c: Context)(xs: c.Expr[Any]*)(i: c.Expr[Int]) = {
import c.universe._
// First let's show that we can recover the types:
println(xs.map(_.actualType))
i.tree match {
case Literal(Constant(index: Int)) => xs.lift(index).getOrElse(
c.abort(c.enclosingPosition, "Invalid index!")
)
case _ => c.abort(c.enclosingPosition, "Need a literal index!")
}
}
}
进而:
scala> Demo.at(1, 'b, "c", 'd')(1)
List(Int(1), Symbol, String("c"), Char('d'))
res0: Symbol = 'b
scala> Demo.at(1, 'b, "c", 'd')(2)
List(Int(1), Symbol, String("c"), Char('d'))
res1: String = c
请注意,推断的类型是精确且正确的。
另请注意,如果参数是带有以下内容的序列,则这将不起作用_*
当然,如果您想捕获这种情况并提供有用的错误消息,则需要编写类似以下内容的内容:
def at_impl(c: Context)(xs: c.Expr[Any]*)(i: c.Expr[Int]) = {
import c.universe._
xs.toList.map(_.tree) match {
case Typed(_, Ident(tpnme.WILDCARD_STAR)) :: Nil =>
c.abort(c.enclosingPosition, "Needs real varargs!")
case _ =>
i.tree match {
case Literal(Constant(index: Int)) => xs.lift(index).getOrElse(
c.abort(c.enclosingPosition, "Invalid index!")
)
case _ => c.abort(c.enclosingPosition, "Need a literal index!")
}
}
}
看我的问题here https://stackoverflow.com/q/13663216/334519和错误报告here https://issues.scala-lang.org/browse/SI-6777进行更多讨论。