Last active
April 9, 2017 12:56
-
-
Save virtualsafety/4f61519a7410ab481e88be8eeaf17645 to your computer and use it in GitHub Desktop.
下面的例子演示了如何利用Quasiquotes来实现Code Generation:
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
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