Frage

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()

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.

War es hilfreich?

Lösung

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)

Then the macro looks like this:

// 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()")
  }
}

And the test case:

// src/test/scala/Test.scala
object Test extends App {
  val fooInt = Foo[Int]
  val fooAny = Foo[Any]

  println(fooInt)
  println(fooAny)
}

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top