使用 Scala 编写脚本:如何启动未编译的脚本? [英] Scripting with Scala: How to launch an uncompiled script?

查看:48
本文介绍了使用 Scala 编写脚本:如何启动未编译的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了严重的性能问题之外,Scala 是一种非常强大的语言.因此,我现在经常将它用于 Bash 中的脚本任务.有没有办法像我对 Python 文件一样执行 *.scala 文件?据我所知,Python 使用字节码来执行程序,就像 JVM 一样.但是,为了完成此操作,我不需要调用任何名为 pythonc(如 scalac 或 javac)的东西.因此,我希望 Scala 能够以类似的方式行事.

Apart from serious performance problems, Scala is a very powerful language. Therefore I am now using it frequently for scripted tasks inside Bash. Is there a way to just execute a *.scala file exactly the way I can do with Python files? As far as I know, Python uses bytecode to execute programs, exactly like the JVM does. However, there is not anything called pythonc (like scalac or javac) I need to call in order to accomplish this. Hence I expect Scala to be able to act in a similar manner.

推荐答案

我不使用 python,但在 Scala 中,我能做的最脚本化的事情是:

I don't use python, but in Scala, the most scripty thing I can do is this:

thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' | scala 
Welcome to Scala version 2.10.2 (Java HotSpot(TM) Server VM, Java 1.7.0_09).
Type in expressions to have them evaluated.
Type :help for more information.

scala> println(" 3 + 4 = " + (3 + 4))
 3 + 4 = 7

scala> thinkpux:~/proj/mini/forum > 

但是,之后,我在 bash 中没有视觉反馈,所以我必须调用clear".

However, afterwards, I don't have visual feedback in the bash, so I have to call 'clear'.

但是编写脚本并执行它没有问题:

But there is no problem in writing a script and executing that:

thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' > print7.scala 
thinkpux:~/proj/mini/forum > scala print7.scala 
 3 + 4 = 7

那么,外壳就没有问题了.

Then, there aren't issues with the shell.

使用封闭类,代码不会被执行:

With an enclosing class, the code wouldn't be executed:

thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\n'
class Foo {
println(" 3 + 4 = " + (3 + 4))
}

thinkpux:~/proj/mini/forum > scala Foo.scala 
thinkpux:~/proj/mini/forum > cat Foo.scala 
class Foo {
println(" 3 + 4 = " + (3 + 4))
}

但是通过实例化一个类,您可以在其中执行代码,而无需使用众所周知的(希望如此)'main' 方式:

But with instatiating a class, you can execute code in it, without using the wellknown (hope so) 'main' way:

thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\nval foo = new Foo()'  > Foo.scala
thinkpux:~/proj/mini/forum > cat Foo.scala 
class Foo {
println(" 3 + 4 = " + (3 + 4))
}
val foo = new Foo()
thinkpux:~/proj/mini/forum > scala Foo.scala 
 3 + 4 = 7

这篇关于使用 Scala 编写脚本:如何启动未编译的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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