gpt4 book ai didi

scala - 如何使用 Scala ScriptEngine 调用函数或模块

转载 作者:行者123 更新时间:2023-12-03 23:16:46 26 4
gpt4 key购买 nike

如何使用 ScriptEngine 调用函数或模块。

这是我的示例代码,编译良好,但在运行时抛出异常 scalaVersion := "2.12.4"and sbt.version = 0.13.16, java is jdk1.8.0_131

import java.io.FileReader
import javax.script._

object DemoApp extends App {
val engine: ScriptEngine with Compilable with javax.script.Invocable = new ScriptEngineManager()
.getEngineByName("scala")
.asInstanceOf[ScriptEngine with javax.script.Invocable with Compilable]
val reader = new FileReader("src/main/scala/Demo.sc")
engine.compile(reader).eval()
val result = engine.invokeFunction("fun")
}

下面是Demo.sc
def fun: String = {
"Rerutn from Fun"
}

以下是运行时的异常
Exception in thread "main" java.lang.ClassCastException: scala.tools.nsc.interpreter.Scripted cannot be cast to javax.script.Invocable
at DemoApp$.delayedEndpoint$DemoApp$1(DemoApp.scala:13)
at DemoApp$delayedInit$body.apply(DemoApp.scala:5)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at DemoApp$.main(DemoApp.scala:5)
at DemoApp.main(DemoApp.scala)

最佳答案

我认为问题在于 Scala 脚本引擎实现了 Compilable ,但不是 Invocable ,这就是为什么你会得到一个类型转换异常。

无论如何,当您调用 eval在编译的结果上,你的代码被执行了,所以你不需要通过 Invocable 调用任何东西.

使用 asInstanceOf有点皱眉头,所以以下更惯用。

试试这个:

import java.io.FileReader
import javax.script._

object DemoApp extends App {
// Get the Scala engine.
val engine = new ScriptEngineManager().getEngineByName("scala")

// See if the engine supports compilation.
val compilerEngine = engine match {
case c: Compilable => Some(c)
case _ => None
}

// If the engine supports compilation, compile and run the program.
val result = compilerEngine.map {ce =>
val reader = new FileReader("src/main/scala/Demo.sc")
ce.compile(reader).eval()
}

println(result.fold("Script not compilable")(_.toString))
}

或者,如果您只想让原始代码正常工作,您应该这样做:

import java.io.FileReader
import javax.script._

object DemoApp extends App {
val engine = new ScriptEngineManager()
.getEngineByName("scala")
.asInstanceOf[ScriptEngine with Compilable]
val reader = new FileReader("src/main/scala/Demo.sc")
val result = engine.compile(reader).eval()
// Output the result
println(result.toString)
}

关于scala - 如何使用 Scala ScriptEngine 调用函数或模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49319402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com