Closure是一个函数,其返回值取决于在此函数外声明的一个或多个变量的值。1
基础2
- 方法 : Scala 中方法是类的一部分
- 函数 : Scala 中函数式一个对象,可以赋值给一个变量
方法
class Test(){
def m(x: Int): Int = {
x+1
}
}
函数
val add = (a:Int, b:Int) => a + b
示例
Demo1
闭包可以访问方法和参数外的变量的函数变量
scala> val number = 10
val number: Int = 10
scala> val add = (a:Int) => { a + number}
val add: Int => Int = $Lambda$1037/1644524251@1d5048d1
scala> add(1)
val res1: Int = 11
Demo2
object Demo0 {
def main(args: Array[String]): Unit = {
//1. 定义函数外变量
val more = 10
//2. 函数的闭包
def makeIncreaser(more) : Int => Int
= (x:Int)=> x + more
// 解释
//2.1. 方法名 : makeIncreaser
//2.2. 参数: more [Scala 自动推算类型] 完整内容 makeIncreaser(more:Int)
//2.3. 返回值: Int => Int (方法,参数和返回值都为Int)
//2.4. 方法体: (x:Int)=> x + more [值,即函数],
//3. 调用函数 - 返回值为函数,类似于 java的函数式接口
val func = makeIncreaser(10)
//4. 调用返回的方法
println(func(11))
//4.1 相当于调用的 func.apply(11) 的方法
}
}
Demo3
import scala.reflect.io.File
object FileMatcher3{
// 使用闭包实现
private def fileHere = new File(".").listFiles()
//1. 传递两个参数
def getFile(files : Array[File], matcher: String => Boolean) = {
for (file <- files ; if matcher(file.getName))
yield file
}
//2. 闭包
def getFile(matcher: String => Boolean) : Array[File] => Array[File] = (files : Array[File]) => {
for (file <- files; if matcher(file.getName))
yield file
}
//3. 闭包
def getFile(files: Array[File]) : (String => Boolean) => Array[File] = (matcher : String => Boolean) => {
for (file <- files; if matcher(file.getName))
yield file
}
def main(args: Array[String]): Unit = {
val stringToBooleanToFiles = getFile(fileHere)
val files = stringToBooleanToFiles(e => e.contains("x"))
}
}
Scala 新手有不好的地方请多指正