闭包的定义:函数里声明函数,函数里面返回函数,就是闭包。任何支持函数式编程的语言都支持闭包。
闭包的作用:
- 让函数成为编程语言中的一等公民
- 让函数具有对象所有的能力
- 让函数具有状态
举几个例子:
fun <T> select(isTrue: Boolean, param1: () -> T, param2: () -> T) = if (isTrue) param1() else param2()
fun ok(): String = "ok"
fun no(): String = "no"
fun main(args:Array<String>) {
println(select(3 > 2, ::ok, ::no))
}
select函数把函数(无参数,返回值为String)作为参数,函数的返回值作为返回值
fun operation(): (Int) -> Int {
return ::square
}
fun square(x: Int) = x * x
var func = operation()
println(func(2))
operation函数把square函数作为返回值
fun justCount():() -> Unit{
var count = 0
return fun(){
println(count++)
}
}
val count = justCount()
count() // 输出结果:0
count() // 输出结果:1
count() // 输出结果:2
此例说明函数具有了状态,count的值被保存了下来