Skip to content

Instantly share code, notes, and snippets.

@virtualsafety
Last active April 9, 2017 12:56
Show Gist options
  • Save virtualsafety/4f61519a7410ab481e88be8eeaf17645 to your computer and use it in GitHub Desktop.
Save virtualsafety/4f61519a7410ab481e88be8eeaf17645 to your computer and use it in GitHub Desktop.
下面的例子演示了如何利用Quasiquotes来实现Code Generation:
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
object HelloQuasiquotes {
def main(args: Array[String]): Unit = {
val universe: scala.reflect.runtime.universe.type = scala.reflect.runtime.universe
import universe._
val toolbox = currentMirror.mkToolBox()
val tree = q"""
val f = {x: Int => x + 1}
f
"""
println(showCode(tree))
val func = toolbox.eval(tree)
val result = func.asInstanceOf[Int => Int](1)
println(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment