Kotlin 函數式編程之 Lambda 與 高階函數《Kotlin 極簡教程》Kotlin 開發者社區

HigherOrderFunctions&Lambda.gif

........

摘自:

《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]
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章