- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 315字
- 2021-06-24 19:15:26
What is functional programming?
Functional programming is a paradigm (a style of structuring your programs). In essence, the focus is on transforming data with expressions (ideally such expressions should not have side effects). Its name, functional, is based on the concept of a mathematical function (not in sub-routines, methods, or procedures). A mathematical function defines a relation between a set of inputs and outputs. Each input has just one output. For example, given a function, f(x) = X2; f(5) is always 25.
The way to guarantee, in a programming language, that calling a function with a parameter always returns the same value, is to avoid accessing to mutable state:
fun f(x: Long) : Long {
return x * x // no access to external state
}
The f function doesn't access any external state; therefore, calling f(5) will always return 25:
fun main(args: Array<String>) {
var i = 0
fun g(x: Long): Long {
return x * i // accessing mutable state
}
println(g(1)) //0
i++
println(g(1)) //1
i++
println(g(1)) //2
}
The g function, on the other hand, depends on mutable state and returns different values for the same.
Now, in a real-life program (a Content Management System (CMS), shopping cart, or chat), state changes. So, in a functional programming style, state management must be explicit and careful. The techniques to manage state change in functional programming will be covered later.
A functional programming style will provide us with the following benefits:
- Code is easy to read and test: Functions that don't depend on external mutable state are more accessible to reason about and to prove
- State and side effects are carefully planned: Limiting state management to individual and specific places in our code makes it easy to maintain and refactor
- Concurrency gets safer and more natural: No mutable state means that concurrency code needs less or no locks around your code
- Learning Chef
- C#編程入門指南(上下冊)
- Raspberry Pi for Secret Agents(Third Edition)
- 匯編語言程序設計(第2版)
- Java持續交付
- Microsoft Azure Storage Essentials
- Mastering Business Intelligence with MicroStrategy
- Python算法詳解
- Learning D
- Oracle Database XE 11gR2 Jump Start Guide
- Laravel Design Patterns and Best Practices
- FusionCharts Beginner’s Guide:The Official Guide for FusionCharts Suite
- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- Mastering Magento Theme Design
- 走近SDN/NFV