How to call a function on an object with a generic type parameter using scala macros?

Viewed 96

Consider the following two classes, both of them have a parseFrom function.

class X {}
object X {
  def parseFrom(b: Array[Byte]): String = "Hello"
}

class Y {}

object Y {
  def parseFrom(b: Array[Byte]): String = "HelloY"
}

I want to write a macro: getParseFrom[X] that will return the X.parseFrom function.

This is what I have so far:

import scala.reflect.macros.whitebox.Context

def getParseFromImpl[T: c.WeakTypeTag](c: Context): c.Tree = {
  import c.universe._
  val tpe = weakTypeOf[T]

  q"""
     $tpe.parseFrom(_)
   """
}

def getParseFrom[T]: Array[Byte] => String = macro getParseFromImpl[T]

Is this possible with scala macros in scala 2.12?

1 Answers

Try

q"""
  ${tpe.typeSymbol.companion}.parseFrom(_)
"""
Related