是否可以从Scala宏内的WeakTypeTag生成Apply? [英] Is it possible to generate Apply from WeakTypeTag inside a scala macro?

查看:73
本文介绍了是否可以从Scala宏内的WeakTypeTag生成Apply?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的宏中有某种类型的WeakTypeTag,我想生成如下代码:

I have a WeakTypeTag of some type in my macro, and I want to generate code as follows:

macroCreate[SomeObject] // => SomeObject(1)

宏的定义如下:

def macroCreate[A] = macro _macroCreate[A]
def _macroCreate[A](c: Context)(implicit wtt: c.WeakTypeTag[A]) = {
  c.Expr(Apply(Select(???, newTermName("apply")), List(c.literal(1).tree)))
}

问题是,如何获取给定类型的Select?

The problem is, how do I get Select for the given type?

我可以使用一种变通方法,将类型转换为字符串,在"."上拆分,然后从字符串列表中创建Select,但这似乎很麻烦.

I can use a workaround of converting the type to string, splitting on "." and then creating a Select from list of strings, but that seems hacky.

是否可以直接从类型标签创建Select?

Is it possible to create a Select directly from type tag?

推荐答案

您可以获取伴随对象的符号,然后使用Universe的Ident(sym: Symbol): Ident工厂方法:

You can get the symbol of the companion object and then use the universe's Ident(sym: Symbol): Ident factory method:

def macroCreate[A] = macro _macroCreate[A]

def _macroCreate[A](c: Context)(implicit wtt: c.WeakTypeTag[A]) = {
  import c.universe._

  c.Expr(
    Apply(
      Select(Ident(wtt.tpe.typeSymbol.companionSymbol), newTermName("apply")),
      c.literal(1).tree :: Nil
    )
  )
}

然后:

scala> case class SomeObject(i: Int)
defined class SomeObject

scala> macroCreate[SomeObject]
res0: SomeObject = SomeObject(1)

scala> macroCreate[List[Int]]
res1: List[Int] = List(1)

如果您真的要说SomeObject是对象的类型(即,不是其伴随类的类型),只需删除上面的.companionSymbol.

If you really mean that SomeObject is the type of the object (i.e., not the type of its companion class), just remove the .companionSymbol above.

这篇关于是否可以从Scala宏内的WeakTypeTag生成Apply?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆