For each iteration of your for loop, yield generates a value which will be remembered. It's like the for loop has a buffer you can't see, and for each iteration of your for loop, another item is added to that buffer. When your for loop finishes running, it will return this collection of all the yielded values. The type of the collection that is returned is the same type that you were iterating over, so a Map yields a Map, a List yields a List, and so on.java
Also, note that the initial collection is not changed; the for/yield construct creates a new collection according to the algorithm you specify.es6
上面那段話的意義就是,for 循環中的 yield 會把當前的元素記下來,保存在集合中,循環結束後將返回該集合。Scala 中 for 循環是有返回值的。若是被循環的是 Map,返回的就是 Map,被循環的是 List,返回的就是 List,以此類推。數組
基於上面的信息,來看幾個例子:oop
scala> for (i <- 1 to 5) yield i res10: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
前面的例子都不算什麼,還只是個開始. 接下來, 對咱們初始集合的每一個元素作一次翻倍:測試
scala> for (i <- 1 to 5) yield i * 2 res11: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)
這裏是 for/yield 循環的求模操做:this
scala> for (i <- 1 to 5) yield i % 2 res12: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 0, 1, 0, 1)
Scala 數組上的 for 循環 yield 的例子es5
以前提到過 for 循環 yield 會構造並返回與給定集合相同類型的集合. 爲此, 咱們來看看如下用 Scala 數組上的例子. 注意把 yield(咱們能夠把 yield 用做一個動詞) 出來的集合類型與前面的幾個例子對比:spa
scala> val a = Array(1, 2, 3, 4, 5) a: Array[Int] = Array(1, 2, 3, 4, 5) scala> for (e <- a) yield e res5: Array[Int] = Array(1, 2, 3, 4, 5) scala> for (e <- a) yield e * 2 res6: Array[Int] = Array(2, 4, 6, 8, 10) scala> for (e <- a) yield e % 2 res7: Array[Int] = Array(1, 0, 1, 0, 1)
正如你所見, 例子中被 yield 的是 Array[Int], 而更早的例子中返回的類型是 IndexedSeq[Int].scala
for 循環, yield, 和守衛( guards) (for loop 'if' conditions)
code
假如你熟悉了 Scala 複雜的語法, 你就會知道能夠在 for 循環結構中加上 'if' 表達式. 它們做爲測試用,一般被認爲是一個守衛,你能夠把它們與 yield 語法聯合起來用。參見::
scala> val a = Array(1, 2, 3, 4, 5) a: Array[Int] = Array(1, 2, 3, 4, 5) scala> for (e <- a if e > 2) yield e res1: Array[Int] = Array(3, 4, 5)
如上, 加上了 "if e > 2" 做爲守衛條件用以限制獲得了只包含了三個元素的數組.
Scala for 循環和 yield 的例子 - 總結
若是你熟悉 Scala 的 loop 結構, 就會知道在 for 後的圓括號中還能夠許更多的事情. 你能夠加入 "if" 表達式,或別的語句, 好比下面的例子,能夠組合多個 if 語句:
def scalaFiles = for { file <- filesHere if file.isFile if file.getName.endsWith(".scala") } yield file
yield 關鍵字的簡短總結:
針對每一次 for 循環的迭代, yield 會產生一個值,被循環記錄下來 (內部實現上,像是一個緩衝區).
當循環結束後, 會返回全部 yield 的值組成的集合.
返回集合的類型與被遍歷的集合類型是一致的.
但願上面的例子結諸位有所幫助.