scala中yield的使用

1、scala中yield的使用

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


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


scala> val filesHere = (new java.io.File(".")).listFiles
filesHere: Array[java.io.File] = Array(./.gnupg, ./Videos, ./.gconf, ./.gstreamer-0.10, ./.gnome2, ./Documents, ./.vim, ./xululog, ./.esd_auth, ./zbx, ./.imsettings.log, ./.ICEauthority, ./bbb, ./.pulse, ./.ssh, ./.bash_history, ./anaconda-ks.cfg, ./.bash_profile, ./.dbus, ./Templates, ./.abrt, ./CDH-5.7.0-1.cdh5.7.0.p0.45-el6.parcel.sha, ./.cache, ./Desktop, ./expect1.sh, ./list, ./install.log.syslog, ./bin, ./.cshrc, ./.config, ./.bashrc, ./.bash_logout, ./clean.sh, ./aaaa, ./H_000017PHIS0000000002_ProCinsured_054.txt, ./Pictures, ./.lesshst, ./.gconfd, ./.viminfo, ./.gvfs, ./.mysql_history, ./patfile, ./install.log, ./expect.sh, ./.gnote, ./.gtk-bookmarks, ./test, ./.tcshrc, ./new.txt, ./.Xauthority, ./slogs, ./Public, ./.nautilus, ./shell, ./Music, ./.local, ./patter, ./test.sh, ./....


scala> def scalaFiles =
     |       for {
     |       file <- filesHere
     |       if file.getName.endsWith(".sh")
     |       } yield file
scalaFiles: Array[java.io.File]

scala> scalaFiles.foreach(println);
./expect1.sh
./clean.sh
./expect.sh
./test.sh

yield 关键字的简短总结:

针对每一次 for 循环的迭代, yield 会产生一个值,被循环记录下来 (内部实现上,像是一个缓冲区).
当循环结束后, 会返回所有 yield 的值组成的集合.
返回集合的类型与被遍历的集合类型是一致的.
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值