Kotlin是一種多范式編程語言,它支持面向對象編程、函數式編程和過程式編程。在Kotlin中,你可以通過以下方式實現函數式編程:
fun applyOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
fun main() {
val sum = applyOperation(5, 3) { x, y -> x + y }
println(sum) // 輸出 8
}
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // 輸出 [2, 4]
inline fun <T> Iterable<T>.forEach(action: (T) -> Unit) {
for (element in this) {
action(element)
}
}
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { println(it) }
}
fun String.hello() = "Hello, $this!"
fun main() {
println("World".hello()) // 輸出 "Hello, World!"
}
val immutableList = listOf(1, 2, 3, 4, 5)
tailrec fun factorial(n: Int, accumulator: Int = 1): Int {
return if (n == 1) accumulator else factorial(n - 1, n * accumulator)
}
fun main() {
println(factorial(5)) // 輸出 120
}
通過使用這些特性,你可以在Kotlin中實現函數式編程風格。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。