如何在scala宏中从带有类型参数的类型中获取类型参数?

How do I get type parameter from type with type parameter, inside scala macro?

我有一个类型(在这种情况下,它表示方法的返回类型),并且它的形式为List[Int](例如)。

我知道类型包含该信息,因为toString会得出正确的值,但是如何提取该类型?我尝试了.typeSymbol,但是这完全丢失了所有类型信息。


您可以使用TypeRef提取器:

1
2
3
4
5
6
7
8
9
10
import reflect.runtime.universe._
// or in a macro"c.universe._"

val tpe = weakTypeOf[List[Int]]

// extract type parameters
val TypeRef(_,_, tps) = tpe

// tps has type List[Type]
println(tps.head) // Int