简体   繁体   English

如何使用 scala 宏在具有泛型类型参数的 object 上调用 function?

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

Consider the following two classes, both of them have a parseFrom function.考虑以下两个类,它们都有一个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.我想编写一个宏: getParseFrom[X] ,它将返回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? scala 2.12 中的 scala 宏是否可以做到这一点?

Try尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM