【发布时间】:2012-07-27 04:50:56
【问题描述】:
我正在使用 2.10.0-M5 使用 Scala 宏,但我无法弄清楚为什么编译器认为返回类型是 Any 而不是 List[Int]。如果我删除对 map 的调用并只返回列表(将宏的最后一行更改为 c.Expr(list)),它会按预期工作。此外,宏确实返回了一个List[Int],编译器只是不知道它。
宏定义:
def test(s:String) = macro testImpl
def testImpl(c:Context)(s:c.Expr[String]):c.Expr[Any] = {
import c.universe._
val list = reify(List(1)).tree
val function = reify((x:Int) => x).tree
val res =
Apply(
Select(
list,
newTermName("map")),
List(function)
)
c.Expr(res)
}
宏调用:
val list:List[Int] = test("")
错误信息:
[error] found : Any
[error] required: List[Int]
[error] val list:List[Int] = test("")
[error] ^
【问题讨论】:
-
我对新的宏系统不太熟悉,但你的
testImpl不应该返回c.Expr[List[Int]]而不是c.Expr[Any]吗? -
在这种情况下,这是一个选择。然而,在我的真实代码中,返回类型取决于宏的参数,所以我事先并不知道。无论如何,如果我删除对 map 的调用,它确实适用于
c.Expr[Any],所以这不是问题。
标签: scala macros scala-2.10