使用Scala宏将符号拼接在一起 [英] Splicing together symbols with Scala macros
问题描述
我正在尝试从通用Scala代码中调用FastUtil或Trove之类的专用集合库.我想实现类似
I am trying to call a specialized collections library like FastUtil or Trove from generic Scala code. I would like to implement something like
def openHashMap[@specialized K, @specialized V]: ${K}2${V}OpenHashMap =
new ${K}2${V}OpenHashMap()
${X}
显然不是有效的Scala,而只是我用于文字替换的元符号,
这样,openHashMap[Long, Double]
将返回Long2DoubleOpenHashMap
,该类型将在编译时知道. Scala宏可以做到这一点吗?如果是这样,哪种口味?我知道有def宏,隐式宏,fundep实现,宏注释,类型宏(现已停产)……我认为在普通的Scala-2.10、2.10宏天堂和Scala-2.11中它们是不同的.其中哪一个适合这个?
Where the ${X}
is clearly not valid Scala, but just my meta notation for text substitution,
so that openHashMap[Long, Double]
would return a Long2DoubleOpenHashMap
the type would be known at compile time. Is this possible with Scala macros. If so, which flavour? I know there are def macros, implicit macros, fundep materialization, macro annotations, type macros (now discontinued) ... and I think these are different in plain Scala-2.10, 2.10 macro paradise and Scala-2.11. Which, if any, of these are appropriate for this?
还是还有其他可以执行此操作的功能,例如字节码操作,语言虚拟化等等?但是,我不相信我刚才提到的替代方法可以.
Or is there something else that can do this like byte code manipulation, language virtualization, ...? However, I do not believe the alternative I just mentioned can.
推荐答案
Stealing the idea to use quasiquotes from this answer, we first add the macro-paradise plugin:
// build.sbt
scalaVersion := "2.10.2"
resolvers += Resolver.sonatypeRepo("snapshots")
addCompilerPlugin("org.scala-lang.plugins" % "macro-paradise" % "2.0.0-SNAPSHOT"
cross CrossVersion.full)
然后宏如下所示:
// src/main/scala/Foo.scala
import reflect.macros.Context
import language.experimental.macros
trait Foo[A]
class IntFoo() extends Foo[Int]
class AnyFoo() extends Foo[Any]
object Foo {
def apply[A]: Foo[A] = macro applyImpl[A]
def applyImpl[A](c: Context)(t: c.WeakTypeTag[A]): c.Expr[Foo[A]] = {
import c.universe._
val aTpe = t.tpe
val prefix = if (aTpe =:= typeOf[Int]) "Int" else "Any"
val clazz = newTypeName(s"${prefix}Foo")
c.Expr(q"new $clazz()")
}
}
测试用例:
// src/test/scala/Test.scala
object Test extends App {
val fooInt = Foo[Int]
val fooAny = Foo[Any]
println(fooInt)
println(fooAny)
}
没有宏天堂插件,您将需要像New(clazz, ???)
那样手动构建树,我无法使它正常工作,所以放弃了,但是当然也有可能.
Without the macro-paradise-plugin, you would need to construct the tree by hand, like New(clazz, ???)
, I couldn't get that to work so gave up, but it certainly would be possible, too.
这篇关于使用Scala宏将符号拼接在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!