1.简化代码
package com.scala.first
import java.io.File
import javax.management.Query
/**
* Created by common on 17-4-5.
*/
object FileMatcher {
def main(args: Array[String]) {
for (file <- filesHere)
println(file)
println()
for (file <- filesMatching("src", _.endsWith(_)))
println(file)
for (file <- filesEnding("src"))
println(file)
}
private def filesHere = (new File(".")).listFiles
//matcher是传入一个函数,返回boolean值,比如_.endsWith(_)
private def filesMatching(query: String, matcher: (String, String) => Boolean) = {
for (file <- filesHere; if matcher(file.getName, query)) yield file
}
//上面的函数不够简洁,下面是更加简洁的定义
private def filesMatch(matcher: String => Boolean) = {
for (file <- filesHere; if matcher(file.getName)) yield file
}
//然后可以定义使用不同matcher()的方法
def filesEnding(query: String) = {
filesMatch(_.endsWith(query))
}
//使用exists来简化代码
def containsOdd(nums: List[Int]): Boolean = {
nums.exists(_ % 2 == 1)
}
def containsNeg(nums: List[Int]): Boolean = {
nums.exists(_ < 0)
}
}
输出是
./.idea ./build.sbt ./target ./input ./project ./src ./src ./src
原文:http://www.cnblogs.com/tonglin0325/p/6718320.html