概念
可以遍历集合并对集合元素处理产生新集合,新集合和原有集合类型相同. (range的不同)
Array,List,Set,Range
本质
语法糖
用法
scala> val s=Array(1,2,3)
s: Array[Int] = Array(1, 2, 3)
//处理Array元素
scala> for(i <-s) yield 2*i
res15: Array[Int] = Array(2, 4, 6)
scala> val p=List(1,2,3)
p: List[Int] = List(1, 2, 3)
//处理List元素
scala> for(i <-p) yield 2*i
res16: List[Int] = List(2, 4, 6)
scala> val q=Set(1,2,3)
q: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
//处理Set元素
scala> for(i <-q) yield 2*i
res17: scala.collection.immutable.Set[Int] = Set(2, 4, 6)
scala> val r=(1,2,3)
r: (Int, Int, Int) = (1,2,3)
//不支持元组
scala> for(i <-r) yield 2*i
<console>:13: error: value map is not a member of (Int, Int, Int)
for(i <-r) yield 2*i
//处理range ^
scala> for(i <- 1 to 10) yield 2*i
res25: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 1
//可以先过滤再生成新集合
scala> for(i <-s if i%2==0) yield 2*i
res23: Array[Int] = Array(4, 8)
//可以先过滤再生成新集合
scala> for(i <-s if i>2) yield 2*i
res24: Array[Int] = Array(6, 8)