官术网_书友最值得收藏!

  • 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
主站蜘蛛池模板: 吉木乃县| 景宁| 镇宁| 宁蒗| 卢湾区| 乐昌市| 沛县| 芷江| 普陀区| 济宁市| 宝鸡市| 太仆寺旗| 珠海市| 肥东县| 咸丰县| 交城县| 湘乡市| 梁平县| 邻水| 双江| 都兰县| 福州市| 姚安县| 沁水县| 怀宁县| 九江市| 海城市| 探索| 裕民县| 乾安县| 浦东新区| 大新县| 建水县| 托克逊县| 宁城县| 枞阳县| 馆陶县| 南京市| 石景山区| 宁化县| 东海县|