Scala中for循环的yield用法

我看了《Programming in Scala》一书,仍然对 Scala yield 关键字的理解不甚清楚。起初我以为 Scala yield 的与 Ruby 的 yield 是一样,Ruby 中 yield 是被传入代码块的占位符。Scala 中的 yield 关键字好像总是在 for 循环中用的. 下面一些例子可以帮助你更好的理解 yield 关键字。下面是摘自 《Programming in Scala》关于 yield 的解释:

For each iteration of your for loop, yield generates a value which will be remembered. It’s like the for loop has a buffer you can’t see, and for each iteration of your for loop, another item is added to that buffer. When your for loop finishes running, it will return this collection of all the yielded values. The type of the collection that is returned is the same type that you were iterating over, so a Map yields a Map, a List yields a List, and so on.

Also, note that the initial collection is not changed; the for/yield construct creates a new collection according to the algorithm you specify.

上面那段话的意义就是,for 循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。Scala 中 for 循环是有返回值的。如果被循环的是 Map,返回的就是 Map,被循环的是 List,返回的就是 List,以此类推。
以上内容转载自https://yanbin.blog/scala-yield-samples-for-loop/ 隔夜黄莺

**

概念

**
for循环中的yield会将for循环中的值保存下来,保存到一个集合中,在循环结束的时候会将集合全部输出,如果被循环的是map,则输出的就是map。如果被循环的是list,则输出的就是list,以此类推。

使用println进行输出

scala> for (i <- 1 to 5)
     | println (i)
1
2
3
4
5

使用yield输出

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

scala> a
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

循环过滤if判断,并返回值

scala> for (e <- a if e % 2 == 0 )
     | yield e
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4)
scala> a
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

scala> val b = 6 to 7
b: scala.collection.immutable.Range.Inclusive = Range(6, 7)

scala> for {
     | x <- a
     | y <- b
     | }
     | yield (x,y)
res7: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,6), (1,7), (2,6), (2,7), (3,6), (3,7), (4,6), (4,7), (5,6), (5,7))

scala> for {
     | y <- b
     | x <- a
     | }
     | yield (x,y)
res8: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,6), (2,6), (3,6), (4,6), (5,6), (1,7), (2,7), (3,7), (4,7), (5,7))

yield复杂点的使用

//找出以固定字符串结尾的文件
scala> def getTextFile(path:String) : Array[java.io.File] =
     | for {
     | file <- new java.io.File(path).listFiles
     | if file.isFile
     | if file.getName.endsWith(".txt")
     | }
     | yield file
getTextFile: (path: String)Array[java.io.File]

scala> getTextFile(".")
res9: Array[java.io.File] = Array(./a.txt)

实际开发中的应用

object Loop {
  def main(args: Array[String]): Unit = {
    val str = Array(1,2,3,4,5,6,7)

    for(i <- str ) {
      println(i)
    }

    val add  = for (i <- str) yield i +100
    println (add.toBuffer)

  }
}

这是输出结果

D:\tools\jdk\bin\java.exe "-javaagent:D:\tools\idea\IntelliJ IDEA 2018.1.6\lib\idea_rt.jar=64772:D:\tools\idea\IntelliJ IDEA 2018.1.6\bin" -Dfile.encoding=UTF-8 -classpath "D:\tools\jdk\jre\lib\charsets.jar;D:\tools\jdk\jre\lib\deploy.jar;D:\tools\jdk\jre\lib\ext\access-bridge-64.jar;D:\tools\jdk\jre\lib\ext\cldrdata.jar;D:\tools\jdk\jre\lib\ext\dnsns.jar;D:\tools\jdk\jre\lib\ext\jaccess.jar;D:\tools\jdk\jre\lib\ext\jfxrt.jar;D:\tools\jdk\jre\lib\ext\localedata.jar;D:\tools\jdk\jre\lib\ext\nashorn.jar;D:\tools\jdk\jre\lib\ext\sunec.jar;D:\tools\jdk\jre\lib\ext\sunjce_provider.jar;D:\tools\jdk\jre\lib\ext\sunmscapi.jar;D:\tools\jdk\jre\lib\ext\sunpkcs11.jar;D:\tools\jdk\jre\lib\ext\zipfs.jar;D:\tools\jdk\jre\lib\javaws.jar;D:\tools\jdk\jre\lib\jce.jar;D:\tools\jdk\jre\lib\jfr.jar;D:\tools\jdk\jre\lib\jfxswt.jar;D:\tools\jdk\jre\lib\jsse.jar;D:\tools\jdk\jre\lib\management-agent.jar;D:\tools\jdk\jre\lib\plugin.jar;D:\tools\jdk\jre\lib\resources.jar;D:\tools\jdk\jre\lib\rt.jar;D:\idea project\HelloScala\out\production\HelloScala;D:\tools\Scala\lib\scala-actors-2.11.0.jar;D:\tools\Scala\lib\scala-actors-migration_2.11-1.1.0.jar;D:\tools\Scala\lib\scala-library.jar;D:\tools\Scala\lib\scala-parser-combinators_2.11-1.0.4.jar;D:\tools\Scala\lib\scala-reflect.jar;D:\tools\Scala\lib\scala-swing_2.11-1.0.2.jar" day03.Loop
1
2
3
4
5
6
7
ArrayBuffer(101, 102, 103, 104, 105, 106, 107)

Process finished with exit code 0

参考

https://unmi.cc/scala-yield-samples-for-loop/

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值