Learning Kotlin (5) Function and Functional Programming

The biggest difference with the functional programming is imperative programming, the focus function that maps programming of data, the focus is imperative programming step to solve the problem .
Functional programming is a way of thinking, its essence is a combination of functions, for example, you want to filter out a List of base, with Kotlin can write:

fun main(args: Array<String>){
   val list = listOf(1, 2 ,3 ,4 ,5, 6, 7)
   println(list.filter{it % 2 == 1 })   //过滤函数,参数是一个lambda表达式
}

1. Introduction to Functional Programming

Functional programming has the following characteristics:

  • First Support Function: function is a data type , can be passed as arguments to another.
  • Pure and invariant functions: pure function refers to a function not to external data not to change state.
  • The combined function: the object-oriented programming is used to build the program logic by sending messages between objects; in functional programming is through through the combination of different functions to build the program logic.

2. function declaration

Is fun to use statement, the following examples can be expressed more intuitive, do also function as a variable to use:

val sum = fun(x: Int, y: Int): Int{ return x + y}

>>>sum
(kotlin.Int, kotin.Int) -> kotlin.Int         //sun是输入是两个Int,输出类型是Int的函数
>>>sum(1, 2)
3

3. Lambda Expressions

He told a beginning the following code:

val list = listOf(1, 2, 3, 4, 5, 6, 7)
list.filter{ it % 2 == 1}

Here the filter () function of the parameters {it% 2 == 1} is a section of a lambda expression.
In fact, since the filter () function only one parameter, the brackets are omitted. Therefore, filter () function call is complete wording:

list.filter({ it % 2 == 1})

//filter()函数声明如下:
public inline fun<T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>

It is a function of the parameter predicate: (T) -> Boolean , in fact, {it % 2 == 1}is a shorthand syntax, complete Lambda expressions are written like this:

{ it -> it % 2 == 1}

If you open to write, it is easier to understand:

val isOdd = { it: Int -> it % 2 == 1}  //直接使用Lambda表达式声明一个函数,这个函数判断输入的Int是不是奇数
val list = listOf({1, 2, 3, 4, 5, 6, 7})
>>> list.filter(isOdd)

4. Higher-order functions

In the λ expression, we have seen a higher-order functions. Now add another layer mapping logic.
We have a list of strings:

val strList = listOf("a", "ab", "abc" ,"abcdef", "abcdefg")

Then we want to filter out the length of the string is a list of odd elements. We solve the problem of the logical split into two functions to achieve a combination of:

val f = fun (x: Int) = x % 2 == 1           //判断输入的Int是否奇数
val g = fun (s: String) = s.lenth           //返回输入的字符串长度

We then use the function h to encapsulate "the length of string elements is an odd number," this logic, as follows:

val h = fun(g: (String) -> Int, f: (Int) -> Boolean): (String) -> Boolean {
    return { f(g(it)) }
}

But the h function declaration too long, but there are simple and easy Kotlin Kotlin type aliases, we use the G, F, H to declare three types of functions:

typealias G = (String) -> Int
typealias F = (Int) -> Boolean
typealias H = (String) -> Boolean

So then we can write:

val h = fun(g: G, f: F): H{
   return { f(g(it)) }    //需要注意的是 {}是不能省略的
}

Code function body { f(g(it)) }, the {} represents a Lambda expression that is returned is a (String) -> Boolean function type. If no {} is the function returns a Boolean value of.
Then use is:

println(strList.filter(h(g,f)))

5. Kotlin the special function

Next comes five special function, run () apply () let () also () with ()

RUN 5.1 ()
RUN () function returns a block (), in fact, incoming calls block parameters, under normal circumstances Lambda is a block of code.

fun testRunFun(){
   myfun()              //直接在代码行调用函数
   run ({ myfun() })    //使用run()函数调用myfun函数
   run { myfun() }      //run()函数的括号 可以省略
   run { println("Rikka") }  //等价于println("Rikka")   
}

5.2 apply ()
source code to show the call block (), the caller returns the current target this.
Means to perform End block () after the code block logic, caller returns the current object again. Test code examples are as follows:

fun testApply(){
   //普通写法
   val list = mutableListOf<String>()
   list.add("A")
   list.add("B")
   println(list)
 
   //apply()写法
   val a = ArrayList<String>().apply {
      add("A")
      add("B")
      println("$this")
   }
   println(a)
   //等价于
   a.let( println(it) )
}

The let 5.3 ()
the let function returns the block (this), meaning that the current caller the object as a parameter block (), the test code is as follows:

fun testLetFun() {
    1.let{ println(it) }       //输出1
    "ABC".let{ println(it) }   //输出ABC,其中it就是调用者ABC
    myfun().let{ println(it) }  //执行fun函数
}

5.4 also ()
first calls the block (this), then return to this

 val a = "ABC".also {
     println(it)    //输出ABC
 }
 println(a)

With 5.4 ()
with () receiver object is passed in a receiver, receiver and then use the object to invoke code block incoming block ()

//常规写法
val list = mutableListOf<String>()
list.add("A")
list.add("B")
println("$list")

//使用with()函数写法
with(ArrayList<String>()){
   add("A")
   add("B)
   println("$this")
}.let{
   println(it)  //kotlin.Unit
}
Published 248 original articles · won praise 99 · Views 100,000 +

Guess you like

Origin blog.csdn.net/rikkatheworld/article/details/102910281