直接執行scala指令,會進入 指令互動環境,你可以輸入-version得知Scala的版本資訊:
>scala -version
Scala code runner version 2.7.7.final -- Copyright 2002-2009, LAMP/EPFL
Scala code runner version 2.7.7.final -- Copyright 2002-2009, LAMP/EPFL
你可以使用-e引數(e是指execute),將一段指令稿送給scala直譯並執行,這適合在懶得進入 指令互動環境,又想了解一小段程式碼的作用或結果時:
>scala -e "println(\"Hello!World!\")"
Hello!World!
>scala -e "val r = 1 + 2; println(r)"
3
Hello!World!
>scala -e "val r = 1 + 2; println(r)"
3
實際上,你可以撰寫一個純文字檔案,建議副檔名為.scala,在當中撰寫Scala程式碼:
- Hello.scala
println("Hello!Scala!")
接著如下執行指令載入指令稿直譯並執行:
>scala Hello.scala
Hello!Scala!
Hello!Scala!
如果你想取得命令列引數(Command line arguments),則可以使用args,例如:
- Hello.scala
println("Hello!" + args(0) + "!")
命令列引數會以字串陣列方式收集並指定給args,注意!args後是()而不是[],Scala中陣列索引的指定方式是(),0表示為第一個命令列引數,1則表示第二個命令列引數,依此類推。接著如下執行指令載入指令稿直譯並執行:
>scala hello.scala caterpillar
Hello!caterpillar!
Hello!caterpillar!
Scala的程式運行於JVM之上,實際上,scala指令會在記憶體中將你的指令稿編譯為位元碼(byte code),而後啟動JVM並執行它(實際上,scala將你的指令稿包裹進一個Main類別的main方法中)。若你願意,可以在執行scala直譯時下-savecompiled引數,將編譯完成的位元碼儲存下來,例如:
>scala -savecompiled Hello.scala caterpillar
Hello!caterpillar!
Hello!caterpillar!
程式如常執行之後,你會發現同一目錄下有個JAR檔案,當中包含了scala所編譯出來的位元碼檔案。
由於scala的程式是運行於JVM之上,你會想要指定一些引數給JVM,同樣是在執行scala時,使用-Dproperty=value的格式來指定。
你可以使用-help取得更多協助訊息:
>scala -help
scalac [ <option> ]... [<torun> <arguments>]
All options to scalac are allowed. See scalac -help.
<torun>, if present, is an object or script file to run.
If no <torun> is present, run an interactive shell.
Option -howtorun allows explicitly specifying how to run <torun>:
script: it is a script file
object: it is an object name
guess: (the default) try to guess
Option -i requests that a file be pre-loaded. It is only
meaningful for interactive shells.
Option -e requests that its argument be executed as Scala code.
Option -savecompiled requests that the compiled script be saved
for future use.
Option -nocompdaemon requests that the fsc offline compiler not be used.
Option -Dproperty=value sets a Java system property.
scalac [ <option> ]... [<torun> <arguments>]
All options to scalac are allowed. See scalac -help.
<torun>, if present, is an object or script file to run.
If no <torun> is present, run an interactive shell.
Option -howtorun allows explicitly specifying how to run <torun>:
script: it is a script file
object: it is an object name
guess: (the default) try to guess
Option -i requests that a file be pre-loaded. It is only
meaningful for interactive shells.
Option -e requests that its argument be executed as Scala code.
Option -savecompiled requests that the compiled script be saved
for future use.
Option -nocompdaemon requests that the fsc offline compiler not be used.
Option -Dproperty=value sets a Java system property.
scala指令可以用來直譯指令稿,也可以用來執行編譯過後的程式碼(也就是位元碼,必須先存在.class檔案),- howtorun可以指定如何執行程式碼,預設是由scala自行猜測。-howtorun指定為script時,直接告知scala指令以直譯方式執 行,可以稍微加快scala開始進行直譯。-howtorun指定object時,程式必須使用scalac編譯為.class,稍後說明。