Scala 如何从M7中的类型获取typeArgs?
我正在将一些代码从Scala 2.10-M5迁移到Scala 2.10-M7。我发现宏上下文中的类型API已显著减少。特别是,我想知道如何获得底层的和类型参数 -- 已更新 按照@EugeneBurmako的要求,我将展示整个画面。假设我们有这种状态:Scala 如何从M7中的类型获取typeArgs?,scala,reflection,macros,scala-2.10,Scala,Reflection,Macros,Scala 2.10,我正在将一些代码从Scala 2.10-M5迁移到Scala 2.10-M7。我发现宏上下文中的类型API已显著减少。特别是,我想知道如何获得底层的和类型参数 -- 已更新 按照@EugeneBurmako的要求,我将展示整个画面。假设我们有这种状态: class Attribute[C[_], E] class Id[E] trait Entity { val att1: List[Int] val att2: Int } object Entity { val att1re
class Attribute[C[_], E]
class Id[E]
trait Entity {
val att1: List[Int]
val att2: Int
}
object Entity {
val att1reif = new Attribute[List, Int]
val att2reif = new Attribute[Id, Int]
}
def Let[T <: Entity, C[_], E](en: T, att: Attribute[C, E], ce: C[E]): T =
/* Updates the whole attribute */
def Let[T <: Entity, C[_], E](en: Entity, att: Attribute[C, E], e: E, mode: Boolean): T =
/* Adds or removes (mode) an item */
具体化属性是冗余的,因此我们希望用户有一个更简单的API。特别是下一个问题:
// Same code as DSL
ent.att1 := List(1, 2, 3)
ent.att1 :+ 4
ent.att1 :- 1
注意,任何地方都没有关于物化的信息。因此,我们需要一些助手和宏观视角来实现我们的目标
trait AttributeHelper {
type T <: Entity
type C[_]
type E
val ent: T
val att: Attribute[C, E]
def :=(ce: C[E]): T = Let(ent, att, ce)
def :+(e: E): T = Let(ent, att, e, true)
def :-(e: E): T = Let(ent, att, e, false)
}
def toAttributeHelperImpl[V: c.AbsTypeTag](c: Context)(expr: c.Expr[V]): c.Expr[AttributeHelper] =
/* A looong macro (currently broken), since I can't split V into C[_] and E,
* which are needed to generate the expression that instantiates an *AttributeHelper*.
* The macro is responsible of finding the attribute reification.
*/
我一直在尝试使用一个使用两个类型参数的宏,但是在这样做时,隐式视图没有被应用(因为编译器无法推断这两种类型)
因此,正如我在开始时提到的,缺少在M5中可用但在M7中不可用的typeArgs打破了以前的宏。如何在没有该def的情况下生成AttributeHelper构造
最后,我必须说前面的代码只是一个简化。还有其他一些相关证据,这就是我需要使用底层的原因。反射API清理(发生在M5前后)背后的一般想法是删除非常特殊的方法 例如,
typeArgs
仅适用于TypeRef
类型,因此将其保留在基类型type
中没有多大意义。替换是一个简单的模式匹配:tpe-match{case-TypeRef(u,u,args)=>arg;case-Nil}
不过,底层的是不同的,因为它是一个内部实现概念,根据类型的具体风格意味着很多事情。如果您详细说明您的用例,我可能会帮助您找到
基础的替代方案。您能否提供示例:1)传入T
的示例,2)您希望通过类型参数得到什么,3)您希望通过基础得到什么。如果我遗漏了什么,请让我知道。
trait AttributeHelper {
type T <: Entity
type C[_]
type E
val ent: T
val att: Attribute[C, E]
def :=(ce: C[E]): T = Let(ent, att, ce)
def :+(e: E): T = Let(ent, att, e, true)
def :-(e: E): T = Let(ent, att, e, false)
}
def toAttributeHelperImpl[V: c.AbsTypeTag](c: Context)(expr: c.Expr[V]): c.Expr[AttributeHelper] =
/* A looong macro (currently broken), since I can't split V into C[_] and E,
* which are needed to generate the expression that instantiates an *AttributeHelper*.
* The macro is responsible of finding the attribute reification.
*/
implicit def toAttributeHelper[V](expr: V): AttributeHelper = macro toAttributeHelperImpl[V]