“评估"在斯卡拉 [英] "eval" in Scala

查看:24
本文介绍了“评估"在斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 能否用于编写 Java 应用程序的脚本?

Can Scala be used to script a Java application?

我需要从 Java 加载一段 Scala 代码,为其设置执行范围(主机应用程序公开的数据),对其进行评估并从中检索结果对象.

I need to load a piece of Scala code from Java, set up an execution scope for it (data exposed by the host application), evaluate it and retrieve a result object from it.

Scala 文档展示了从 Java 调用已编译的 Scala 代码是多么容易(因为它会变成常规的 JVM 字节码).

The Scala documentation shows how easy it is to call compiled Scala code from Java (because it gets turned into to regular JVM bytecode).

但是我如何即时评估 Scala 表达式(从 Java 或者如果这更容易,从 Scala 内部)?

But how can I evaluate a Scala expression on the fly (from Java or if that is easier, from within Scala) ?

对于许多其他语言,有 javax.scripting 接口.Scala 似乎不支持它,我在 Java/Scala 互操作性文档中找不到任何不依赖于提前编译的内容.

For many other languages, there is the javax.scripting interface. Scala does not seem to support it, and I could not find anything in the Java/Scala interoperability docs that does not rely on ahead-of-time compilation.

推荐答案

Scala 不是脚本语言.它可能看起来有点像脚本语言,人们可能为此而提倡它,但它并不真正适合 JSR 223 脚本框架(面向动态类型语言).为了回答您最初的问题,Scala 没有 eval 函数,就像 Java 没有 eval 一样.鉴于它们本质上是静态的,这样的函数对于这两种语言中的任何一种都没有真正意义.

Scala is not a scripting language. It may look somewhat like a scripting language, and people may advocate it for that purpose, but it doesn't really fit well within the JSR 223 scripting framework (which is oriented toward dynamically typed languages). To answer your original question, Scala does not have an eval function just like Java does not have an eval. Such a function wouldn't really make sense for either of these languages given their intrinsically static nature.

我的建议:重新考虑你的代码,这样你就不需要 eval(你很少这样做,即使在有它的语言中,比如 Ruby).或者,也许您根本不想在应用程序的这一部分使用 Scala.如果您确实需要 eval,请尝试使用 JRuby.JRuby、Scala 和 Java 结合得非常好.让系统的一部分使用 Java,一部分使用 Scala,另一部分(需要 eval 的部分)使用 Ruby,这很容易.

My advice: rethink your code so that you don't need eval (you rarely do, even in languages which have it, like Ruby). Alternatively, maybe you don't want to be using Scala at all for this part of your application. If you really need eval, try using JRuby. JRuby, Scala and Java mesh very nicely together. It's quite easy to have part of your system in Java, part in Scala and another part (the bit which requires eval) in Ruby.

这篇关于“评估"在斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆