Scala 学习之 for 循环- yield 学习

本文详细介绍了Scala中的for循环和yield的使用,包括它们如何保存和返回集合,以及如何在循环中添加条件(guards)进行过滤。通过多个示例展示了在数组、Map等数据结构上应用for/yield的技巧,强调了yield关键字在生成集合时的作用和返回类型的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

我们先看下scala的 for循环骚操作:

scala> for (i <- 1 to 3; j <-1 to 3 if i!=j )
                   println(s"i=$i,j=$j,i+j=${i+j}")

        i=1,j=2,i+j=3
        i=1,j=3,i+j=4
        i=2,j=1,i+j=3
        i=2,j=3,i+j=5
        i=3,j=1,i+j=4
        i=3,j=2,i+j=5

 

    for循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。Scala中for循环是有返回值的。如果被循环的是Map,返回的就是Map,被循环的是List,返回的就是List,以此类推。

例1:

scala> for (i <- 1 to 5) yield i
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

例2:

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

例3: for/yield 循环的求模操作:

 scala> for (i <- 1 to 5) yield i % 2
 res3: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 0, 1, 0, 1)

例4:Scala 数组上的 for 循环 yield 的例子

  scala> val a = Array(1, 2, 3, 4, 5)
  a: Array[Int] = Array(1, 2, 3, 4, 5)
   
  scala> for (e <- a) yield e
  res4: Array[Int] = Array(1, 2, 3, 4, 5)
   
  scala> for (e <- a) yield e * 2
  res5: Array[Int] = Array(2, 4, 6, 8, 10)
   
 scala> for (e <- a) yield e % 2
 res6: Array[Int] = Array(1, 0, 1, 0, 1)

例5:for 循环, yield, 和守卫( guards) (for loop 'if' conditions)

假如你熟悉了 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
  res7: Array[Int] = Array(3, 4, 5)

加上了 "if e > 2" 作为守卫条件用以限制得到了只包含了三个元素的数组.

例6: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 的值组成的集合.
  • 返回集合的类型与被遍历的集合类型是一致的.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值