我正在try Graalvm非常酷的Polyglot特性,这样我就可以从Scala应用程序判断Python.
测试REPL代码如下.如果我运行它,并输入以下代码,我可以很好地计算v.__add__(1)
.我明白了:
>>> v
evaluating v
evaluated got Value(7)
>>> v.__add__(1)
evaluating v.__add__(1)
evaluated got Value(8)
>>>
有没有办法判断v + 1
?
当我try 的时候,我得到TypeError: unsupported operand type(s) for +: 'foreign' and 'int'
分.
以下是测试REPL代码:
import org.graalvm.polyglot.{Context, Source}
import scala.annotation.targetName
import scala.util.control.NonFatal
case class Value(v: Int) {
@targetName("__add__")
def +(i: Int): Value = Value(v + i)
}
class Python(context: Context, v: Value) {
private val language = "python"
context.getBindings(language).putMember("v", v)
def eval(code: String): AnyRef = {
try {
val source = Source
.newBuilder(language, code, "<shell>")
.interactive(false)
.buildLiteral()
println(s"evaluating $code")
val res = context.eval(source)
println(s"evaluated got $res")
res
} catch {
case NonFatal(e) =>
println(s"error evaluating $code")
e.printStackTrace()
null
}
}
}
object Python {
def main(args: Array[String]): Unit = {
val context = Context
.newBuilder("python")
.allowAllAccess(true)
.build()
val python = new Python(context, Value(7))
while (true) {
val line = scala.io.StdIn.readLine(">>> ")
python.eval(line)
}
}
}