Android开发Android进阶Android开发经验谈

Kotlin局部函数与Lambda表达式

2019-07-22  本文已影响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表达式可以脱离函数独立使用。

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
上一篇 下一篇

猜你喜欢

热点阅读