Step into Kotlin - 20 - 高阶函数
来源:互联网 发布:大众软件 pdf 编辑:程序博客网 时间:2024/06/01 13:13
目录
- 高阶函数
- 概念
- 函数字面值
- 函数作为参数
- 闭包与柯理化
- 方法扩展表达式
- inline 注解
- 高阶函数
摘要
函数字面值,函数参数,闭包与柯理化,方法扩展表达式,inline
高阶函数
概念
那些以函数作为参数或返回函数的函数被称为高阶函数。
函数字面值
Kotlin 中函数可以赋值给变量
两种写法
val sum = { x: Int, y: Int -> x + y }val sum2: (Int, Int) -> Int = { x, y -> x + y }
函数作为参数
格式
(函数参数) => 返回值类型
fun add(f: (Int) -> Int) = f(10)val x = add({ Int -> 2 })println(x) //2
以上 add 函数接收另一个函数作为参数,并在函数体内调用此函数,所以 add 函数即为高阶函数。
闭包与柯理化
- 闭包指由代码和非局部变量的自由变量组成的代码块
- 柯理化指接收参数产生新的函数的函数,所以柯理化函数也是高阶函数
var sum3 = 0val ints = intArrayOf(1, 2, 3)ints filter { it > 0 } forEach { sum3 += it}print(sum3)
方法扩展表达式
val sum4 = fun Int.(other: Int): Int = this + other1.sum4(2)1 sum4 2
inline 注解
每个方法实际都是一个包含 Lambda 表达式的对象,inline 注解可以将每个 Lambda 表达式进行内联以提高性能,noinline 则相反。
inline fun inlineLock<T>(lock: Lock, body: () -> T, @noinline notInlined: () -> T): T { lock.lock() try { return body() } finally { lock.unlock() }}
0 0
- Step into Kotlin - 20 - 高阶函数
- Step into Scala - 20 - 高阶函数
- Step into Kotlin - 04 - 函数
- Step into Kotlin
- Step into Kotlin - 01 - 入门
- Step into Kotlin - 02 - 数据类型
- Step into Kotlin - 06 - 异常
- Step into Kotlin - 08 - 数组
- Step into Kotlin - 09 - 集合
- Step into Kotlin - 11 - 类
- Step into Kotlin - 13 - 包
- Step into Kotlin - 14 - 继承
- Step into Kotlin - 15 - 注解
- Step into Kotlin - 17 - 泛型
- Step into Kotlin - 22 - Xml
- Step into Kotlin - 24 - delegate
- Step into Kotlin - 05 - 流程控制
- Step into Kotlin - 12 - Object 与枚举
- Android4.0强制横屏竖屏
- [iOS/Swift]String的 toInt() 和 integerValue 的区别
- 2.12-三目运算符
- signal(SIGPIPE, SIG_IGN)
- android界面响应事件
- Step into Kotlin - 20 - 高阶函数
- 【经验交流】我为什么要帮你?
- 2 括号配对问题【栈】
- Android 挂起/继续过程分析
- 推荐 15 个 jQuery 选择框插件
- OC学习
- JSTL函数fn.tld
- android-async-http-master - 网络连接
- asp.net中BeginInvoke和EndInvoke方法使用方法