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 的值组成的集合.
返回集合的类型与被遍历的集合类型是一致的.