Type mismatch in scala quasiquote of macro definition: “type mismatch; found : field.NameType required: c.universe.TermName”

烂漫一生 提交于 2020-01-15 12:18:06

问题


I asked a longer question, but it seems it's too much code for people to sort through so I've created this question to focus on one smaller, specific problem I'm facing regarding use of macros in Scala.

Consider the following code snippet:

val tpe = weakTypeOf[T]
val companion = tpe.typeSymbol.companionSymbol

val fields = tpe.declarations.collectFirst {
  case m: MethodSymbol if m.isPrimaryConstructor => m
}.get.paramss.head

val toMapParams = fields.map { field =>
  val name = field.name
  val decoded = name.decoded
  q"$decoded -> t.$name"
}

Note that fields is just the list of parameters for the primary constructor of a case class in this code. Where I'm confused is the result of the quasiquote q"$decoded -> t.$name". What does this mean exactly? And what type should it have? I'm getting a compile error stating the following:

Multiple markers at this line
    - Implicit conversions found: q"$decoded -> t.$name" => Quasiquote(q"$decoded -> t.
     $name")
    - type mismatch; found : field.NameType required: c.universe.TermName
    - type mismatch; found : field.NameType required: c.universe.TermName

Can anyone explain this error? Thanks.


回答1:


The type of fields is List[Symbol], which means that the type of names of those fields is inconclusive (unknown whether it's a TermName or TypeName). This means that you can't insert such names essentially anywhere in a quasiquote.

A simple fix would be to do val name = field.name.toTermName, explicitly telling the compiler that it's looking at a term name, so that quasiquote knows how to process it.



来源:https://stackoverflow.com/questions/23946187/type-mismatch-in-scala-quasiquote-of-macro-definition-type-mismatch-found-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!