The example illustrating the problem:
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]
*/
Why did we lost the concrete type in foo2
? It looks very similar to foo1
.
PS: I've found a solution which could be not the best:
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]
*/
But an answer for the question is still interesting to me.
type Lambda
def foo2[A]: Unit = macro impl[A, {type A = Option[Int]}]
def impl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: blackbox.Context): c.Expr[Unit] = {
import c.universe._
//Option[Int]
println(c.weakTypeOf[B].members.find(_.isType).get.typeSignature)
reify(())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.