结构子类型反射

时间:2012-11-01 21:01:30

标签: scala reflection structural-typing

我们可以使用函数val s: String外部的反射来获取f的类型吗?

val f = (r: {val s: String}) => {
}

1 个答案:

答案 0 :(得分:10)

scala> import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{universe=>ru}

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> def typeOf[T: ru.TypeTag](x: T) = ru.typeOf[T] // capture compile-time type info
typeOf: [T](x: T)(implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type

scala> val f = (r: {val s: String}) => {}
f: AnyRef{val s: String} => Unit = <function1>

scala> val tpe = typeOf(f)
tpe: reflect.runtime.universe.Type = scala.AnyRef{val s: String} => Unit

scala> ru.showRaw(tpe)
res0: String = TypeRef(ThisType(scala), scala.Function1, List(RefinedType(List(TypeRef(ThisType(scala), newTypeName("AnyRef"), List())), Scope(newTermName("s"))), TypeRef(ThisType(scala), scala.Unit, List())))

scala> val ru.TypeRef(_, _, refinement :: _) = tpe
refinement: reflect.runtime.universe.Type = scala.AnyRef{val s: String}

使用Scala反射,还可以为结构类型生成模拟,如下所示:https://gist.github.com/4008389。链接的要点使用工具箱和运行时反射执行此操作,但此方案看起来也可以通过宏实现。