通過Scala的名為args的陣列可以獲得傳遞給Scala腳本的命令行參數。Scala裡,陣列以零開始,通過在括號裡指定索引訪問一個元素。所以Scala裡陣列steps的第一個元素是steps(0),不是像Java裡的steps[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
:
#!/bin/sh
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!