栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Scala - 闭包(Closure)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Scala - 闭包(Closure)

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 新手有不好的地方请多指正

参考内容
  1. WIKI教程 - Scala -Closure ↩︎

  2. 菜鸟教程-Scala - 方法与函数 ↩︎

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731619.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号