//闭包
//函数运行的环境就是闭包
//持有函数的运行环境
//函数内部可以定义函数 也可以定义类
val string = "hello world"
fun makeFun():()->Unit{
var count = 0
return fun(){
println(++count)
}
}
fun fibonacci():()->Long{
var first = 0L
var second = 1L
return fun():Long{
val result = second
second+=first
first = second-first
return result
}
}
fun fibonacci1(): Iterable<Long> {
var first = 0L
var second = 1L
data class Person(val name:String)
return Iterable {
object:LongIterator(){
override fun hasNext() = true
override fun nextLong(): Long {
val result = second
second+=first
first = second-first
return result
}
}
}
}
fun add(x:Int)=fun(y:Int) = x+y
fun add1(x:Int):(Int)->Int{
return fun(y:Int):Int{
return x+y
}
}
fun main(args: Array<String>) {
val x = makeFun()
x()
x()
x()//函数的作用域没有被释放
val f = fibonacci()
println(f())
println(f())
println(f())
for(i in fibonacci1()){
if(i > 100)break
println(i)
}
var add5 = add(5)
println(add5(2))
}
kotlin 函数闭包
最新推荐文章于 2024-06-19 17:02:57 发布