scala - What are the ways to convert a String into runnable code? -
i not find how convert string runnable code, instance:
val = "new string('yo')" // conversion println(i)
should print
yo
after conversion.
i found following example in post:
import scala.tools.nsc.interpreter.iloop import java.io.stringreader import java.io.stringwriter import java.io.printwriter import java.io.bufferedreader import scala.tools.nsc.settings object funcrunner extends app { val line = "sin(2 * pi * 400 * t)" val lines = """import scala.math._ |var t = 1""".stripmargin val in = new stringreader(lines + "\n" + line + "\nval f = (t: int) => " + line) val out = new stringwriter val settings = new settings val looper = new iloop(new bufferedreader(in), new printwriter(out)) val res = looper process settings console println s"[$res] $out" }
link: how convert string text input function in scala
but seems scala.tools not available anymore, , i'm newbie in scala not figure out how replace it. , may there other ways now.
thanks !
you can simple execute code contained inside string using quasiquotes(experimental module).
import scala.reflect.runtime.universe._ import scala.reflect.runtime.currentmirror import scala.tools.reflect.toolbox // compile , run code use toolbox api. val toolbox = currentmirror.mktoolbox() // write code starting q , put inside double quotes. // note : have use triple quotes if have double quotes usage in code. val code1 = q"""new string("hello")""" //compile , run code. val result1 = toolbox.compile(code1)() // example val code2 = q""" case class a(name:string,age:int){ def f = (name,age) } val = new a("your name",22) a.f """ val result2 = toolbox.compile(code2)()
output in repl :
// exiting paste mode, interpreting. import scala.reflect.runtime.universe._ import scala.reflect.runtime.currentmirror import scala.tools.reflect.toolbox toolbox: scala.tools.reflect.toolbox[reflect.runtime.universe.type] = scala.tools.reflect.toolboxfactory$toolboximpl@69b34f89 code1: reflect.runtime.universe.tree = new string("hello") result1: = hello code2: reflect.runtime.universe.tree = { case class extends scala.product scala.serializable { <caseaccessor> <paramaccessor> val name: string = _; <caseaccessor> <paramaccessor> val age: int = _; def <init>(name: string, age: int) = { super.<init>(); () }; def f = scala.tuple2(name, age) }; val = new a("your name", 22); a.f } result2: = (your name,22) scala>
to learn more quasiquotes : http://docs.scala-lang.org/overviews/quasiquotes/setup.html
nice post.
ReplyDeletescala training