Kotlin闭包(支持函数式编程不再是梦想)

简介: 一、闭包 闭包目前非常火,因为闭包的出现,现在支持函数式编程就不再是梦想了。二、什么是闭包 1.函数的运行环境 2.

一、闭包
闭包目前非常火,因为闭包的出现,现在支持函数式编程就不再是梦想了。

二、什么是闭包
1.函数的运行环境
2.持有函数运行状态
3.函数内部可以定义函数
4.函数内部也可以定义类

三、来看一下小例子

package net.println.kotlin.chapter5.closure

import java.util.*

/**
 * @author:wangdong
 * @description:
 */
val string = "HelloWorld"

/**定义一个函数*/
fun makeFun():() -> Unit{
    var count = 0
    //返回一个匿名函数,打印一下
    return fun(){
        println(++count)
    }
}

/**再定义个fibonacci方法,斐波拉契序列*/
fun fibonacci(): Iterable<Long>{
    var first = 0L
    var second = 1L
    return Iterable {
        object : LongIterator(){
            override fun nextLong(): Long {
                val result = second
                second += first
                first = second - first
                return result
            }

            override fun hasNext() = true

        }

    }
}

fun main(args: Array<String>) {
    val x = makeFun()
    //每调一次count就会加一
    x()
    for (i in fibonacci()){
        if (i > 100)break
        println(i)
    }

    //第一步add5中x等于13
    //第一次传13进来,x=13,返回回去add5中x=13
    val add5 = add(13)
    //第二步中,y等于56,这个时候,要返回x+y了
    //最后13+56=69
    println(add5(56))
    //69
}

//fun add(x: Int) = fun(y: Int) = x + y
//函数套函数
fun add(x: Int):(Int) -> Int{
    //x=13
    return fun(y:Int):Int{
        //y=56
        return x+y
    }
    //最终69
}

好了,结束了!

目录
相关文章
|
5月前
|
缓存 Kotlin Python
|
3月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
|
4月前
|
缓存 Kotlin Python
Kotlin - 函数式编程
Kotlin - 函数式编程
|
4月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
55 5
|
5月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
59 2
|
5月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
57 1
|
5月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
63 6
|
5月前
|
缓存 Kotlin Python
Kotlin教程笔记(25) -函数式编程
Kotlin教程笔记(25) -函数式编程
|
Java Kotlin
Kotlin中函数式编程的详解
Kotlin中函数式编程的详解
118 0
|
Java Kotlin
Kotlin中匿名函数(又称为Lambda,或者闭包)和高阶函数的详解
Kotlin中匿名函数(又称为Lambda,或者闭包)和高阶函数的详解
171 0