for循環中的 yield 會把當前的元素記下來,保存在集合中,循環結束后將返回該集合。Scala中for循環是有返回值的。如果被循環的是Map,返回的就是Map,被循環的是List,返回的就是List,以此類推。
例1:
1 scala> for (i <- 1 to 5) yield i 2 res10: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
例2:
1 scala> for (i <- 1 to 5) yield i * 2 2 res11: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)
例3: for/yield 循環的求模操作:
1 scala> for (i <- 1 to 5) yield i % 2 2 res12: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 0, 1, 0, 1)
例4:Scala 數組上的 for 循環 yield 的例子
1 scala> val a = Array(1, 2, 3, 4, 5) 2 a: Array[Int] = Array(1, 2, 3, 4, 5) 3 4 scala> for (e <- a) yield e 5 res5: Array[Int] = Array(1, 2, 3, 4, 5) 6 7 scala> for (e <- a) yield e * 2 8 res6: Array[Int] = Array(2, 4, 6, 8, 10) 9 10 scala> for (e <- a) yield e % 2 11 res7: Array[Int] = Array(1, 0, 1, 0, 1)
例5:for 循環, yield, 和守衛( guards) (for loop 'if' conditions)
假如你熟悉了 Scala 復雜的語法, 你就會知道可以在 for 循環結構中加上 'if' 表達式. 它們作為測試用,通常被認為是一個守衛,你可以把它們與 yield 語法聯合起來用。參見::
1 scala> val a = Array(1, 2, 3, 4, 5) 2 a: Array[Int] = Array(1, 2, 3, 4, 5) 3 4 scala> for (e <- a if e > 2) yield e 5 res1: Array[Int] = Array(3, 4, 5)
加上了 "if e > 2" 作為守衛條件用以限制得到了只包含了三個元素的數組.
例6:Scala for 循環和 yield 的例子 - 總結
如果你熟悉 Scala 的 loop 結構, 就會知道在 for 后的圓括號中還可以許更多的事情. 你可以加入 "if" 表達式,或別的語句, 比如下面的例子,可以組合多個 if 語句:
1 def scalaFiles = 2 for { 3 file <- filesHere 4 if file.isFile 5 if file.getName.endsWith(".scala") 6 } yield file
yield 關鍵字的簡短總結:
- 針對每一次 for 循環的迭代, yield 會產生一個值,被循環記錄下來 (內部實現上,像是一個緩沖區).
- 當循環結束后, 會返回所有 yield 的值組成的集合.
- 返回集合的類型與被遍歷的集合類型是一致的.
轉自:http://unmi.cc/scala-yield-samples-for-loop/感謝作者無私分享!