Skip to content

Instantly share code, notes, and snippets.

@dragos
Created November 16, 2015 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dragos/7a3093357f848eb09419 to your computer and use it in GitHub Desktop.
Save dragos/7a3093357f848eb09419 to your computer and use it in GitHub Desktop.
Reflect on singleton types
package test
// prints:
//
// test.Main.C prefix value: test.Main$@54a097cc
// test.Main.o.D prefix value: Outer(o)
object Main {
val universe = scala.reflect.runtime.universe
val mirror = universe.runtimeMirror(getClass.getClassLoader)
import universe._
case class C(x: Int)
case class Outer(name: String) {
case class D(x: Int)
}
val o = Outer("o")
def main(args: Array[String]): Unit = {
printInfo(typeOf[C])
printInfo(typeOf[o.D])
}
def printInfo(t: Type) {
t match {
case TypeRef(pre, sym, args) =>
println(s"$t prefix value: ${singleValue(pre)}")
}
}
def singleValue(t: Type): Any = t match {
case ThisType(sym) =>
mirror.reflectModule(sym.companionSymbol.asModule).instance
case SingleType(pre, x) =>
val v = singleValue(pre)
val m = pre.member(x.name).asTerm
mirror.reflect(v).reflectField(m).get
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment