scala中有许多方式去循环集合for
loops, while
loops, 和集合中的方法诸如 foreach
, map
, flatMap,这节主要说明for的用法和for的翻译(translated)
1、for的用法
val a = Array("apple","banana", "orange")
//for 循环
for(item <- a) println(item)
for(item <- a){
val s = item.toUpperCase()
println(s)
}
//带有返回值的for循环
for(item <- a) yield item.toUpperCase() foreach print
//val new_a = for(item <- a) yield item.toUpperCase()
println
//使用数字循环数组
for(item <- 0 until a.length ) println(s"$item is ${a(item)}")
//Scala集合还提供了一个zipWithIndex方法,您可以使用它们来创建一个循环计数器
for((e, count) <- a.zipWithIndex ) println(s"$count is $e")
//使用if守卫来进行判断过滤
for((e, count) <- a.zipWithIndex if e.contains("e")) println(s"$count is $e")
//Looping over a Map
val map = Map("fname" -> "Robert", "lname" -> "Goren")
for((key,value) <- map) println(s"$key=$value")
2、for的翻译(translated
)
/**
* How for loops are translated
* 使用scalac -Xprint:parse ForScala.scala 来进行编译
* 1、for循环遍历 被转换成foreach方法调用的集合
* source:
* for (i <- 1 to 10) println(i)
* compiler:
* 1.to(10).foreach(((i) => println(i)))
* 2、for循环中的if守护条件其实是使用了withFilter调用序列的集合
* source:
* for (i <- 1 to 10 if i < 5) println(i)
* compiler:
* 1.to(10).withFilter(((i) => i.$less(5))).foreach(((i) => println(i)))
* 3、for循环中的yield表达式被转换成map方法调用的集合
* source:
* for (i <- 1 to 10) yield i * 2
* compiler:
* 1.to(10).map(((i) => i.$times(2)))
* 4、for循环中既包含if守护又包含yield转换成 先withFilter调用序列的集合 在map方法调用的集合
*/