0

I'm writing some macros in Scala.

Let's assume I have some Type, e.g. typeOf[Map[String,Set[Int]]] and a similar type where some of its parts have been replaced with undetermined type parameters, e.g. typeOf[Map[String,Set[T]]] where T is unknown.

How do I match these two types with each other to find out that T is Int?

ghik
  • 10,706
  • 1
  • 37
  • 50

2 Answers2

0

typeArgs property return the list of type parameters. If I correctly understood what do you need:

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
Archeg
  • 8,364
  • 7
  • 43
  • 90
  • That was just an example. I want a general method that would work for all types :) – ghik Dec 02 '15 at 17:05
  • In that case you could match over `typeArgs` and recursively go deeper. I don't think scala has any easier way of matching types, although I could be mistaken. – Archeg Dec 02 '15 at 17:08
  • that would be easy if it was just for type arguments. There are also singleton types, refined types, variance comes into play, etc. This is probably not trivial to write by hand. – ghik Dec 02 '15 at 19:11
0

you can try to use 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
}
余杰水
  • 1,404
  • 1
  • 11
  • 14