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 - 方法与函数 ↩︎

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值