7-3 《Scala编程》 内建的控制结构 - for表达式
说明:
①在for表达式中,“file <- files”叫做生成器(generator)
②嵌套循环可以写在一个for里
③可以为每个生成器添加if过滤器(filter)
④trimmed是一个中途绑定的变量
⑤for表达式可以有返回值,将yeild放在代码体之前。
代码
import java.io.File
import scala.io.Source
object Test {
def main(args: Array[String]): Unit = {
println(grep(".+").mkString("\n\r"))
}
def fileLines(file: File): List[String] = {
Source.fromFile(file).getLines().toList
}
def grep(pattern: String): Array[String] = {
val files: Array[File] = new File(".").listFiles()
for {
file <- files
if file.getName.contains(".")
if file.getName.endsWith(".xml")
line <- fileLines(file)
trimmed = line.trim
if trimmed.matches(pattern)
}yield file + ": " + trimmed
}
}
控制台输出
.\pom.xml: <?xml version="1.0" encoding="UTF-8"?> .\pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" .\pom.xml: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .\pom.xml: xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> .\pom.xml: <modelVersion>4.0.0</modelVersion> .\pom.xml: <groupId>org.example</groupId> .\pom.xml: <artifactId>scala-demo</artifactId> .\pom.xml: <version>1.0-SNAPSHOT</version> .\pom.xml: </project>

浙公网安备 33010602011771号