Scala的for循环以及field、守卫(guard)笔记

Scala中的yield的是把每次迭代中的有关值,并逐一存入到一个集合中,返回值类型和for循环中的返回值类型一致。

eg1.for循环

//to
scala> for(i <- 2 to 10)
     | print(i+" ")
2 3 4 5 6 7 8 9 10
//until
scala> for(i <- 2 until 10)
     | print(i+" ")
2 3 4 5 6 7 8 9
//定义一个数组
scala> val a = Array(1,3,5,7,9)
a: Array[Int] = Array(1, 3, 5, 7, 9)
//隔两个数迭代
scala> for(a <- 0 until (a.length,2)) yield a
res35: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4)
//遍历
scala> for (elem <- a) yield elem
res24: Array[Int] = Array(1, 3, 5, 7, 9)

eg2.不对yield迭代后的结果做任何处理

scala> for (i <- 1 to 10) yield i
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

eg3.yield迭代后,集合中每个元素乘以3

scala> for (i <- 1 to 10) yield i*3
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

eg4.守卫(guards)即在for循环中,加上if判断条件,对进行yield的值做限制

scala> for (i <- 1 to 10 if i%2 ==0) yield i*3
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(6, 12, 18, 24, 30)

ps:其他方法

scala> a.filter(_ % 3 == 0).map(2 * _)
res45: Array[Int] = Array(6, 18)
//或者
scala> a.filter(_ % 3 == 0) map(2 * _)//可以使用花括号
res46: Array[Int] = Array(6, 18)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值