scala> val arr = Array[Int](1,2,3,4,5) arr: Array[Int] = Array(1, 2, 3, 4, 5) scala> for (i<-arr){} scala> for (i<-arr){println(i)} 1 2 3 4 5 角標來取值 scala> arr(2) res2: Int = 3 scala> var idx = Array(0,1,2,3,4) idx: Array[Int] = Array(0, 1, 2, 3, 4) scala> for(i<-idx){println(arr(i))} scala> 1 to 10 res4: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> 1.to(10) res5: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> 0 until 5 res7: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4) scala> for(ele <- 0 to 5) println(arr(ele)) 1 2 3 4 5 java.lang.ArrayIndexOutOfBoundsException: 5 at $anonfun$1.apply$mcVI$sp(<console>:13) at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160) ... 32 elided scala> for (ele <- 0 until arr.length) println(arr(ele)) 1 2 3 4 5 scala> arr res9: Array[Int] = Array(1, 2, 3, 4, 5) scala> for (ele <- arr){ | if (ele%2==0) println(ele) | } 2 4 scala> for (ele <- arr;if ele%2==0) println(ele) 2 4 scala> for (ele <- arr if ele%2==0) println(ele) 2 4 雙層for循環 scala> for(i <- 1 to 3;j <- 1 to 3 if i != j) println(10*i+j) 12 13 21 23 31 32 scala> for(i <- 1 to 3;j <- 1 to 3 if i != j) yield(10*i+j) res15: scala.collection.immutable.IndexedSeq[Int] = Vector(12, 13, 21, 23, 31, 32) 運算符重載 操做符重載成方法 scala> 1.+(2) res16: Int = 3