Created
November 16, 2015 15:56
-
-
Save dragos/7a3093357f848eb09419 to your computer and use it in GitHub Desktop.
Reflect on singleton types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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