Last active
August 29, 2015 14:22
-
-
Save matsu-chara/e34bc9b03674a20c9f41 to your computer and use it in GitHub Desktop.
TypeDynamicの練習
This file contains hidden or 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
name := "TypeDynamic" | |
version := "1.0" | |
scalaVersion := "2.11.6" | |
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value |
This file contains hidden or 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 TypeDynamic | |
import scala.language.experimental.macros | |
import scala.reflect.macros.whitebox | |
import scala.reflect.macros.whitebox.Context | |
object TypeDynamic { | |
class Example() extends Dynamic { | |
val value: Int = 2 | |
def selectDynamic(name: String): Int = macro selectDynamicImpl | |
} | |
def selectDynamicImpl(c: whitebox.Context)(name: c.Expr[String]): c.Expr[Int] = { | |
import c.universe._ | |
val nameStr: String = name.tree match { | |
case pq"${n: String}" if n.startsWith("_") => n.drop(1) | |
case _ => c.abort(c.enclosingPosition, s"#$name not found.") | |
} | |
c.Expr[Int](q"${c.prefix}.${TermName(nameStr)}") | |
} | |
} |
This file contains hidden or 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 TypeDynamic | |
import TypeDynamic._ | |
object TypeDynamicTest { | |
def main(args: Array[String]): Unit = { | |
val e = new Example() | |
println(e._value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment