Kotlin局部函数与Lambda表达式

作者: 程序员丶星霖 | 来源:发表于2019-07-22 17:30 被阅读1次

Lambda表达式是现代编程语言争相引入的一种语法,Lambda表达式是功能更灵活的代码块,可以在程序中被传递和调用。

一、使用Lambda表达式代替局部函数

使用Lambda表达式简化之前的getMathFunc函数。

fun main(args: Array<String>) {
    var mathFunc = getMathFunc("square")
    println(mathFunc(5))
    mathFunc = getMathFunc("cube")
    println(mathFunc(5))
    mathFunc = getMathFunc("other")
    println(mathFunc(5))
}

fun getMathFunc(type: String): (Int) -> Int {
    when (type) {
        //调用局部函数
        "square" -> return { n: Int ->
            n * n
        }
        "cube" -> return { n: Int ->
            n * n * n
        }
        else -> return { n: Int ->
            var result = 1
            for (index in 2..n) {
                result *= index
            }
            result
        }
    }
}

输出结果:

25
125
120

使用Lambda表达式与局部函数存在如下区别:

  • Lambda表达式总是被大括号括着。
  • 定义Lambda表达式不需要fun关键字,无须指定函数名。
  • 形参列表在->之前声明,参数类型可以省略。
  • 函数体放在->之后。
  • 函数的最后一个表达式自动被作为Lambda表达式的返回值,无须使用return关键字。

二、Lambda表达式的脱离

作为函数参数传入的Lambda表达式可以脱离函数独立使用。

import java.util.ArrayList

fun main(args: Array<String>) {
    collectFn { it * it }
    collectFn { it * it * it }
    println(lambdaList.size)
    for (i in lambdaList.indices) {
        println(lambdaList[i](i + 10))
    }
}

//定义一个List类型的变量,并将其初始化为空List
var lambdaList = ArrayList<(Int) -> Int>()

//定义一个函数,该函数的形参类型为函数
fun collectFn(fn: (Int) -> Int) {
    lambdaList.add(fn)
}

输出结果:

2
100
1331

把Lambda表达式作为参数传给collectFn()函数之后,Lambda表达式可以脱离collectFn()函数使用。

学海无涯苦作舟

我的微信公众号.jpg

相关文章

网友评论

    本文标题:Kotlin局部函数与Lambda表达式

    本文链接:https://www.haomeiwen.com/subject/xqlpfctx.html