天天看点

Kotlin 函数式编程之 Lambda 与 高阶函数

Kotlin 函数式编程之 Lambda 与 高阶函数

HigherOrderFunctions&Lambda.gif

Kotlin 函数式编程之 Lambda 与 高阶函数
Kotlin 函数式编程之 Lambda 与 高阶函数

........

摘自:

​​《Kotlin 极简教程》​​

源代码:

package com.light.sword.coursera

val lengthFun = fun(s: String): Int = s.length //lengthFun is a fun variable
val isOddFun = fun(x: Int): Boolean = x % 2 != 0

fun compose(length: (String) -> Int, isOdd: (Int) -> Boolean): (String) -> Boolean {
    return { x -> isOdd(length(x)) }
}

fun main(args: Array<String>) {
    val words = listOf("Hello", "U", "Kotlin", "Java")
    val result = words.filter(compose(lengthFun, isOddFun)) // Use lengthFun directly
    println(result) // [Hello, U]
}      
Kotlin 函数式编程之 Lambda 与 高阶函数

Kotlin 开发者社区

国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

继续阅读