关于kotlin:Kotlin-高阶函数介绍

8次阅读

共计 1900 个字符,预计需要花费 5 分钟才能阅读完成。

什么是高阶函数

将函数作为参数或者返回值的,称高阶函数。

定义高阶函数

action 是一个高阶函数,(Int) -> Int 示意是函数的类型,(Int)示意函数入参类型为 Int,前面的 Int 示意函数返回类型。

    private fun init() {val action: ((Int) -> Int) = {// 函数进行加 100 运算
            it + 100
        }
    }
函数作为参数

以下代码,init 函数调用 doSomething 函数,将 Int 类型 0 以及 action 函数传入 doSomething。doSomething 函数先对入参 0 进行加 200 运算,而后调用高阶函数 action(进行加 100 运算),最初打印后果 actionResult。是不是有点策略设计模式的滋味?是的,齐全能够用它来实现策略设计模式。

    private fun init() {val action: ((Int) -> Int) = {// 函数进行加 100 运算
            it + 100
        }
        doSomething(0, action)// 将 0 以及 action 传给 doSomething
    }

    private fun doSomething(d: Int, action: (Int) -> Int) {
        val data = d + 200// 先对 d 进行加 200 运算
        val actionResult = action(data)// 将加 200 后的后果传给 action,后果保留在 actionResult 中
        Log.e("test", "actionResult=${actionResult}")// 打印后果
    }
函数作为返回值

以下代码,依据不同的类型 type,返回对应的 action,接着对参数 0 进行运算,最初打印后果。

    override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val action = init("计划 1")
        // 获取到对应的 action,传入参数 0 进行运算
        val result = action?.invoke(0)
        // 打印后果
        Log.e("test", "result=${result}")
    }


    private fun init(type: String): ((Int) -> Int)? {val action1: ((Int) -> Int) = {// 加 100 运算
            it + 100
        }

        val action2: ((Int) -> Int) = {// 加 200 运算
            it + 200
        }
        // 依据类型 type,返回对应的 action
        return when (type) {
            "计划 1" -> action1
            "计划 2" -> action2
            else -> null
        }
    }
lamdba 表达式

也是高阶函数,只不过函数是匿名的。以下代码性能跟上述一样,只不过用 amdba 表达式代替了定义 action 函数。

private fun init() {doSomething(0) { // 将 0 以及 lambda 表达式传给 doSomething
        it + 100// 进行加 100 运算, 并返回
    }
}

private fun doSomething(d: Int, action: (Int) -> Unit) {
    val data = d + 200// 先对 d 进行加 200 运算
    val actionResult = action(data)// 将加 200 后的后果传给 action,后果保留在 actionResult 中
    Log.e("test", "actionResult=${actionResult}")// 打印后果
}
高阶函数实质是什么呢?

将第一个例子反编译

private static final void init() {Function1 action = new Function1() {//1
        @Override
        public Object invoke(Object o) {return ((Integer)o).intValue() + 100;//2}
    };
    doSomething(0, action);
}

private static final void doSomething(int d, Function1 action) {//3
    int data = d + 200;
    int actionResult = ((Number)action.invoke(data)).intValue();
    Log.e("test", "actionResult=" + actionResult);
}
  • 正文 1:Kotlin 编译器将高阶函数转成 Function1;
  • 正文 2:对应高阶函数的实现;
  • 正文 3:调用高阶函数,其实就是触发 invoke 函数;

以上剖析有不对的中央,请指出,互相学习,谢谢哦!

正文完
 0