Skip to content

Instantly share code, notes, and snippets.

@vsuharnikov
Created July 1, 2017 08:37
Show Gist options
  • Save vsuharnikov/1a30cc2a7899b7dc33ce33187c02afa8 to your computer and use it in GitHub Desktop.
Save vsuharnikov/1a30cc2a7899b7dc33ce33187c02afa8 to your computer and use it in GitHub Desktop.
Partially applied macros
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object Test {
def foo1[A, B]: Unit = macro impl[A, B]
def foo2[A]: Unit = macro impl[A, Option[Int]]
def impl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: blackbox.Context): c.Expr[Unit] = {
import c.universe._
c.echo(c.enclosingPosition, s"A=${weakTypeOf[A]}, B=${weakTypeOf[B]}")
reify(())
}
}
/*
scala> Test.foo1[Int, Option[Int]]
<console>:12: A=Int, B=Option[Int]
Test.foo1[Int, Option[Int]]
^
scala> Test.foo2[Int]
<console>:12: A=Int, B=Option[A] // <--- Expected: A=Int, B=Option[Int]
Test.foo2[Int]
*/
@vsuharnikov
Copy link
Author

Solution:

import scala.language.experimental.macros
import scala.reflect.macros.blackbox
import scala.reflect.runtime.universe.TypeTag

object Test {
  def foo1[A, B](implicit bTag: TypeTag[B]): Unit = macro impl[A, B]
  def foo2[A](implicit bTag: TypeTag[Option[Int]]): Unit = macro impl[A, Option[Int]]

  def impl[A: c.WeakTypeTag, B](c: blackbox.Context)(bTag: c.Expr[TypeTag[B]]): c.Expr[Unit] = {
    import c.universe._
    c.echo(c.enclosingPosition, s"A=${weakTypeOf[A]}, B=${bTag.actualType.typeArgs.head}")
    reify(())
  }
}

/*
scala> Test.foo1[Int, Option[Int]]
<console>:12: A=Int, B=Option[Int]
       Test.foo1[Int, Option[Int]]
                ^

scala> Test.foo2[Int]
<console>:12: A=Int, B=Option[Int]
       Test.foo2[Int]
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment