【问题标题】:Is it possible to defer macro expansion until abstract type is bound to specific type是否可以推迟宏扩展,直到抽象类型绑定到特定类型
【发布时间】:2012-08-28 18:27:37
【问题描述】:

我可能使用了不正确的术语,但这里是我想要实现的示例。假设我有以下宏:

def generateField[T]: AnyRef =
  macro generateFieldImpl[T]

def generateFieldImpl[T: c.AbsTypeTag](c: Context): c.Expr[AnyRef] = {
/**
 * here I'm looking at the type T by reflection to see now many members it has
 * and based on that I'm generating TupleN[Array[Byte], ...](null, ...)
 * where N is number of members in class represented by type T
 */
}

我打算只使用案例类作为 T。

当我将此宏与案例类一起使用时效果很好,但现在我想添加一个抽象级别:

trait WithGeneratedField[T] {
  val _myField = generateField[T]
}

我遇到的问题是宏在声明 trait 时被扩展,此时 T 被称为抽象类型“T”。有什么方法可以推迟宏扩展,直到我将这个特性与具体的东西混合在一起?例如:

case class MyClass(a: String, b: Int) extends WithGeneratedField[MyClass]

最后,我的目标是使用宏将生成的字段添加到案例类中。也许有更好的方法来做到这一点?

【问题讨论】:

    标签: scala reflection macros


    【解决方案1】:

    如果这在 2.10.0 中成为可能,我会感到惊讶。

    使用宏类型或宏注释 (http://scalamacros.org/future.html) 应该非常简单。我们将在发布 2.10.0-final 后立即着手处理这些新的宏风格,但很难预测 ETA。也许是 2012 年冬天 - 2013 年春天。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2021-08-20
      • 2018-06-12
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多