環境: CentOS 6.3
不解釋,看例子,自己琢磨。
1. While 循環
$ cat while.scala
var i = 10;
while ( i > 0 ) {
println("this is number " + i);
i = i -1;
}
$ scala while.scala
this is number 10
this is number 9
this is number 8
this is number 7
this is number 6
this is number 5
this is number 4
this is number 3
this is number 2
this is number 1
2. foreach 循環
$ cat foreach.scala
var array=new Array[String](3) //創建數組並初始化
array(0) = "hello"
array(1) = "nihao"
array(2) = "ma?"
array.foreach(arr => println(arr)) // 用foreach 循環輸出數組內容 arr是指array裏面每個元素的參數,scala 會推斷是string
//array.foreach((arr:String) => println(arr)) //也可以顯示指定arr類型
3. for 循環
$ cat for.scala
for(arg<-args)
println(arg)
$ scala for.scala this is China
this
is
China
總結,函數式文本的語法: