匹配两种类型以确定类型参数

时间:2015-12-02 14:09:15

标签: scala reflection scala-macros

我在Scala中写了一些宏。

我们假设我有一些Type,例如typeOf[Map[String,Set[Int]]]和类似的类型,其中某些部分已被未确定的类型参数替换,例如typeOf[Map[String,Set[T]]]其中T未知。

如何将这两种类型相互匹配,以确定TInt

2 个答案:

答案 0 :(得分:0)

typeArgs属性返回类型参数列表。如果我正确理解你需要什么:

val mapParams = typeOf[Map[String, Set[Int]]].typeArgs // List(String, Set[Int])
val setType = mapParams.drop(1).head                   // Set[Int]
val setParam = setType.typeArgs.head                   // Int

答案 1 :(得分:0)

您可以尝试使用quasiquotes doc:http://docs.scala-lang.org/overviews/quasiquotes/syntax-summary.html

import scala.reflect.runtime.universe._

tq"Map[Int,Int]" match {
  case tq"Map[Int,$t2]" => t2
}

tq"Map[Int,Seq[Int]]" match {
  case tq"Map[Int,Seq[$t2]]" => t2
}