Scala Script

Scala 可以 Scripting 的方式, 執行. 但這並非 Scala 的強項, 而僅是在展示它的眾多特性之一, 不過倒也可以用於作業系統管理與任務工作, 如果你願意的話 - WisdomFish.ORG

Main class

Scala 對於 Script 與靜態方法例如 main( ) 的執行都是化為
scala.tools.nsc.MainGenericRunner (scala-complier.jar)
中的 main( ) 來進行

def main(args: Array[String]) { }

Script 用的特殊 args(0..N)


  • args.length

注意 Java 的 ++i 和 i++ 在 Scala 裡不起作用.


i 從 0 到 n

scala hello.scala args(0)

Write some Scala scripts

Although Scala is designed to help developers build large systems, it also scales down nicely such that it feels natural to write scripts in it. A script is just a sequence of statements in a file that will be executed sequentially. (By the way, if you're still running the scala interpreter, you can exit it by entering the :quit command.) Put this into a file named hello.scala:

println("Hello, world, from a script!")

then run:

$scala hello.scala

And you should get yet another greeting:

Hello, world, from a script!

Command line arguments to a Scala script are available via a Scala array named args. In Scala, arrays are zero based, as in Java, but you access an element by specifying an index in parentheses rather than square brackets. So the first element in a Scala array named steps is steps(0), not steps[0]. To try this out, type the following into a new file named helloarg.scala:

// Say hello to the first argument
println("Hello, " + args(0) + "!")

then run:

>scala helloarg.scala planet

In this command, "planet" is passed as a command line argument, which is accessed in the script as args(0). Thus, you should see:

Hello, planet!

Note also that this script included a comment. As with Java, the Scala compiler will ignore characters between // and the next end of line, as well as any characters between /* and */. This example also shows strings being concatenated with the + operator. This works as you'd expect. The expression "Hello, " + "world!" will result in the string "Hello, world!".

Unix Shell

By the way, if you're on some flavor of Unix, you can run a Scala script as a shell script by prepending a 「pound bang」 directive at the top of the file. For example, type the following into a file named helloarg:

exec scala $0 $@

// Say hello to the first argument
println("Hello, " + args(0) + "!")

The initial #!/bin/sh must be the very first line in the file. Once you set its execute permission:

>chmod +x helloarg

You can run the Scala script as a shell script by simply saying:

>./helloarg globe

Which should yield:

Hello, globe!