如何为Scala(2.12)宏使用泛型?

时间:2019-01-21 00:44:23

标签: scala scala-macros scala-quasiquotes

我已经定义了一个简单的通用宏:

object MyMacro {

  def readWrite[T](readParse: String => T, label: String, format: T => String): Unit = macro readWriteImpl[T]

  def readWriteImpl[T: c.WeakTypeTag](c: Context)(readParse: c.Expr[String => T], label: c.Expr[String], format: c.Expr[T => String]): c.Tree = {
    import c.universe._

    q"""
    def read[WIRE](path: Path, reader: Transceiver[WIRE], isMapKey: Boolean = false): T =
      reader.readString(path) match {
        case null => null.asInstanceOf[T]
        case s => Try( $readParse(s) ) match {
          case Success(d) => d
          case Failure(u) => throw new ReadMalformedError(path, "Failed to parse "+$label+" from input '"+s+"'", List.empty[String], u)
        }
      }

    def write[WIRE](t: T, writer: Transceiver[WIRE], out: Builder[Any, WIRE]): Unit =
      t match {
        case null => writer.writeNull(out)
        case _    => writer.writeString($format(t), out)
      }
      """
  }
}

在一个单独的编译单元中,我像这样使用它:

object DurationTypeAdapterFactory extends TypeAdapter.=:=[Duration] {
  MyMacro.readWrite[Duration]((s: String) => Duration.parse(s), "Duration", (t: Duration) => t.toString)
}

编译后,编译器会抱怨它不了解T:

[error] /Users/me/git/ScalaJack/core/src/main/scala/co.blocke.scalajack/typeadapter/TimePrimitives.scala:13:30: not found: type T
[error]   MyMacro.readWrite[Duration]((s: String) => Duration.parse(s), "Duration", (t: Duration) => t.toString)
[error] 

我不太理解准引用中的“ T”引用。我该如何在准引用中表示传递给readWriteImpl的T参数,以便正确解压缩?

1 个答案:

答案 0 :(得分:2)

使用标签检查类型,或使用=:=将其与其他类型进行比较,或在扩展中使用它。

例如,

scala 2.13.0-M5> def fImpl[A: c.WeakTypeTag](c: Context)(a: c.Expr[A]) = { import c._, universe._
               | q"null.asInstanceOf[${implicitly[c.WeakTypeTag[A]].tpe}]" }
fImpl: [A](c: scala.reflect.macros.blackbox.Context)(a: c.Expr[A])(implicit evidence$1: c.WeakTypeTag[A])c.universe.Tree

scala 2.13.0-M5> import language.experimental.macros ; def f[A](a: A): A = macro fImpl[A]
import language.experimental.macros
defined term macro f: [A](a: A)A

scala 2.13.0-M5> f(42)
res2: Int = 0

scala 2.13.0-M5> f("")
res3: String = null