Last active
May 15, 2016 10:35
-
-
Save petitviolet/4c446066da25c150a0eb50b39b4522d3 to your computer and use it in GitHub Desktop.
Nashorn Example
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
import javax.script._ | |
object NashornExample extends App { | |
val ENGINE_NAME = "nashorn" | |
val engine = new ScriptEngineManager() | |
.getEngineByName(ENGINE_NAME) | |
.asInstanceOf[ScriptEngine with Invocable] | |
val fName = "func" | |
val f = s"""function $fName(a, b) { return a + b; };""" | |
engine.asInstanceOf[Compilable].compile(f).eval() | |
val argments = Seq(1, 2) map { _.asInstanceOf[AnyRef] } | |
val result = engine.invokeFunction(fName, argments: _*) | |
println(s"result => $result") | |
} | |
object NashornTypingExample extends App { | |
val ENGINE_NAME = "nashorn" | |
val engine = new ScriptEngineManager() | |
.getEngineByName(ENGINE_NAME) | |
.asInstanceOf[ScriptEngine with Invocable with Compilable] | |
case class User(id: Long, name: String) | |
// use Scala type in JavaScript | |
val fName = "f" | |
val f = | |
s""" | |
|function $fName(user) { | |
| return "id: " + user.id() + ", name: " + user.name(); | |
|}; | |
|""".stripMargin | |
engine.compile(f).eval() | |
val result1 = engine.invokeFunction(fName, User(1, "alice")) | |
println(s"result1 => $result1") | |
// casting JavaScript result to Scala type | |
val gName = "g" | |
val g = | |
s""" | |
|function $gName(id, name) { | |
| var User = Java.type("NashornTypingExample.User"); | |
| return new User(id, name); | |
|}; | |
|""".stripMargin | |
engine.compile(g).eval() | |
val result2 = engine.invokeFunction(gName, Seq(2, "bob") map {_.asInstanceOf[AnyRef]} :_*) | |
println(s"result2 => $result2") | |
println(s"result2 => ${result2.asInstanceOf[User].name}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run result is below.