title: How to use scala macros to create a function object (to create a Map[String, (T) => T])
body: <p>I am trying to use Scala macros to create a case class map of single-parameter <code>copy</code> methods, with each method accepting a Play Json <code>JsValue</code> and a case class instance, and returning an updated copy of the instance.  However, I am running into problems with the macro syntax for returning a function object.</p>
  
  <p>Given a case class</p>
  
  <pre><code>case class Clazz(id: Int, str: String, strOpt: Option[String])
  </code></pre>
  
  <p>the intention is to create a map of the class's copy methods</p>
  
  <pre><code>implicit def jsonToInt(json: JsValue) = json.as[Int]
  implicit def jsonToStr(json: JsValue) = json.as[String]
  implicit def jsonToStrOpt(json: JsValue) = json.asOpt[String]
  
  Map("id" -&gt; (json: JsValue, clazz: Clazz) = clazz.copy(id = json),
    "str" -&gt; (json: JsValue, clazz: Clazz) = clazz.copy(str = json), ...)
  </code></pre>
  
  <p>I have found two related questions:</p>
  
  <p>Using macros to create a case class field map: <a href="https://stackoverflow.com/questions/17223213/scala-macros-making-a-map-out-of-fields-of-a-class-in-scala">Scala Macros: Making a Map out of fields of a class in Scala</a></p>
  
  <p>Accessing the case class copy method using a macro: <a href="https://stackoverflow.com/questions/13446528/howto-model-named-parameters-in-method-invocations-with-scala-macros">Howto model named parameters in method invocations with Scala macros?</a></p>
  
  <p>...but I am stuck at how I can create a function object so that I can return a <code>Map[String, (JsValue, T) =&gt; T]</code></p>
  
  <hr>
  
  <p>Edit: Thanks to Eugene Burmako's suggestion to use quasiquotes - this is where I'm currently at using Scala 2.11.0-M7, basing my code on <a href="http://blog.echo.sh/post/65955606729/exploring-scala-macros-map-to-case-class-conversion" rel="nofollow noreferrer">Jonathan Chow's post</a> (I switched from using (T, JsValue) => T to (T, String) => T to simplify my REPL imports)</p>
  
  <p>Edit2: Now incorporating $tpe splicing</p>
  
  <pre><code>import scala.language.experimental.macros
  
  implicit def strToInt(str: String) = str.toInt
  
  def copyMapImpl[T: c.WeakTypeTag](c: scala.reflect.macros.Context): 
      c.Expr[Map[String, (T, String) =&gt; T]] = {
  
    import c.universe._
  
    val tpe = weakTypeOf[T]
  
    val fields = tpe.declarations.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor =&gt; m
    }.get.paramss.head
  
    val methods = fields.map { field =&gt; {
      val name = field.name
      val decoded = name.decoded
      q"{$decoded -&gt; {(t: $tpe, str: String) =&gt; t.copy($name = str)}}"
    }}
  
    c.Expr[Map[Sring, (T, String) =&gt; T]] {
      q"Map(..$methods)"
    }
  }
  
  def copyMap[T]: Map[String, (T, String) =&gt; T] = macro copyMapImpl[T]
  
  case class Clazz(i: Int, s: String)
  
  copyMap[Clazz]
  </code></pre>