Nashorn is a built-in Java 8 JavaScript engine.
Scala 2.12 & Java 8 are wonderful together. Let's have a look!
import javax.script.ScriptEngineManager
import scala.beans.BeanProperty
object NashornScalaInteraction extends App {
/** Creates .setTransformer() and .getTransformer() which Nashorn can access **/
/** Nashorn supports working with SAM directly, so Scala methods interoperate directly with JavaScript **/
@BeanProperty
var transformer: String => String = { str => str.trim }
configureArguments()
printOutput()
def printOutput(): Unit = {
List("1", "2", " 3 ").map(transformer).foreach(println)
}
def configureArguments(): Unit = {
val scriptingEngine = new ScriptEngineManager().getEngineByName("javascript")
scriptingEngine.put("me", this)
args.sliding(2).collect {
case Array("--js", command) =>
command
}.foreach(scriptingEngine.eval)
}
}
$ sbt stage
...
$ ./target/universal/stage/bin/scala-nashorn-config --js 'me.transformer = function(x) x + x;'
11
22
3 3
build.sbt
scalaVersion := "2.12.1"
enablePlugins(JavaAppPackaging)
project/snp.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4")
Well, that was easy!
Never ever forget that you're in the Java Land ;)
#Scala #Nashorn #JVM #Java interaction. SO SIMPLE with Scala 2.12 and JDK 8!https://t.co/FbvkffA6Hl
— William Narmontas (@ScalaWilliam) December 29, 2016