我试图为我的Play Framework项目制作一个宏(2.3.7)。我试图将anorm Row映射到案例类变得容易。当我尝试编译附加的代码时,我得到以下异常:
[error] ***:15: exception during macro expansion:
[error] java.util.NoSuchElementException: None.get
[error] at scala.None$.get(Option.scala:322)
[error] at scala.None$.get(Option.scala:320)
[error] at ***.ModelMacros$.reads(ModelMacros.scala:29)
import anorm._
import scala.reflect.macros.whitebox
import scala.language.experimental.macros
object ModelMacros {
implicit def sqlMapper[T]: Row => T = macro reads[T]
def reads[T: c.WeakTypeTag](c: whitebox.Context): c.Expr[Row => T] = {
import c.universe._
val t = weakTypeOf[T]
val companion = t.typeSymbol.companion
val fields = t.declarations.collectFirst {
case m: MethodSymbol if m.isPrimaryConstructor ⇒ m
}.get.paramLists.head
val fromMapParams = fields.map { field =>
val name = field.name.toTermName
val decoded = name.decodedName.toString
val returnType = t.decl(name).typeSignature
val fixedName = camelToUnderscores(decoded)
q"row[$returnType]($fixedName)"
}
c.Expr[Row => T] {
q"""
{ row => $companion(..$fromMapParams) }
"""
}
}
}
我不明白如何使通用T适当地反映出来。任何帮助将不胜感激。谢谢!