Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active May 15, 2016 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petitviolet/4c446066da25c150a0eb50b39b4522d3 to your computer and use it in GitHub Desktop.
Save petitviolet/4c446066da25c150a0eb50b39b4522d3 to your computer and use it in GitHub Desktop.
Nashorn Example
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}")
}
@petitviolet
Copy link
Author

petitviolet commented May 15, 2016

run result is below.

$ scalac NashornExample.scala
$ scala NashornExample
result => 3
$ scala NashornTypingExample
result1 => id: 1, name: alice
result2 => User(2,bob)
result2 => bob

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment