Rog*_*ach 6 macros scala scala-2.10 scala-macros
以下是一个明显的可变函数:
def fun(xs: Any*) = ???
Run Code Online (Sandbox Code Playgroud)
我们可以用类似的方式定义一个宏:
def funImpl(c: Context)(xs: c.Expr[Any]*) = ???
fun(1,"1",1.0)
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,所有参数都被输入为Any.实际上,编译器在编译时知道类型,但是将它隐藏起来.是否有可能得到的参数列表,并在宏它们的类型?
Sure—for example:
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!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
And then:
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
Run Code Online (Sandbox Code Playgroud)
Note that the inferred types are precise and correct.
另请注意,如果参数是具有_*类型ascription 的序列,当然,如果要捕获此情况并提供有用的错误消息,则需要编写类似以下内容的内容:
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!")
}
}
}
Run Code Online (Sandbox Code Playgroud)