for循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。Scala中for循环是有返回值的。若是被循环的是Map,返回的就是Map,被循环的是List,返回的就是List,以此类推。es6
例1:数组
1 scala> for (i <- 1 to 5) yield i 2 res10: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
例2:oop
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 的例子es5
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)spa
假如你熟悉了 Scala 复杂的语法, 你就会知道能够在 for 循环结构中加上 'if' 表达式. 它们做为测试用,一般被认为是一个守卫,你能够把它们与 yield 语法联合起来用。参见::scala
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" 做为守卫条件用以限制获得了只包含了三个元素的数组.code
例6:Scala for 循环和 yield 的例子 - 总结blog
若是你熟悉 Scala 的 loop 结构, 就会知道在 for 后的圆括号中还能够许更多的事情. 你能够加入 "if" 表达式,或别的语句, 好比下面的例子,能够组合多个 if 语句:get
1 def scalaFiles = 2 for { 3 file <- filesHere 4 if file.isFile 5 if file.getName.endsWith(".scala") 6 } yield file
yield 关键字的简短总结:
转自:http://unmi.cc/scala-yield-samples-for-loop/感谢做者无私分享!