Introduction and actual combat of Android kotlin high-order functions and Java lambda expressions

1. Introduction

        At present, with the continuous improvement of the Java JDK version, new expressions have begun to appear, but in the development of Android confusion, the language of kotlin and the language of Java are closely related. So Java lambda expressions appear in Kotlin with a new identity: higher-order functions are very similar to lambda expressions. Next, I will talk about Java's lambda first, and then introduce kotlin's higher-order functions.

2. Introduction and practice of Java lambda expressions

2.1 Introduction to expression format of lambda

1. No parameters are required, and the return value is 5  
() -> 5  
  
 2. Receive a parameter (number type) and return its double value  
x -> 2 * x  
  
 3. Accept 2 parameters (numbers) and return their difference  
(x, y) -> x – y  
  
 4. Receive 2 int integers and return their sum  
(int x, int y) -> x + y  
  
5. Accept a string object and print it on the console without returning any value (it looks like returning void)  
(String s) -> System.out.print(s)

It can be roughly divided into several categories:

1. There are parameters but no return value (String msg) ->

2. Return value without parameters ()->Int

3. There are parameters and return values ​​(int a, int b) -> ()

2.2 Actual Combat

        Java lambda expressions are defined through interfaces. An interface can only define one type. The specific logic needs to be defined through Java lambda. Interfaces only want to be one type

interface Add {
    int add(int a, int b); //返回值
}

An Add type is defined above,

Add add = (int a, int b) -> (a + b);//什么+
Add sub = (int a, int b) -> (a - b);//申明-
Add mul = (int a, int b) -> (a * b);//申明

Three lambda operators are defined through the Add type. This is done

use

1. The first type executes itself through the operator type

public int operation(int a, int b, Add add) {
    return add.add(a, b);
}

2. Call directly

add.add(10, 20)

2.3 Practical Demo

public class TestJava {


    @Test
    public void main() {
        TestJava tester = new TestJava();


        Back back = () -> 4;

        Log log = (String msg) -> com.example.lib.Log.INSTANCE.log(msg);
        //单个形参,可以不用注明变量类型
        Log log1 = msg -> com.example.lib.Log.INSTANCE.log(msg);

        Add add = (int a, int b) -> (a + b);//什么+
        Add sub = (int a, int b) -> (a - b);//申明-
        Add mul = (int a, int b) -> (a * b);//申明


        com.example.lib.Log.INSTANCE.log("back=" + back);
        log.log("我调用了Log");
        com.example.lib.Log.INSTANCE.log("add=" + add.add(10, 20));
        tester.operation(50, 10,add);
        tester.operation(50, 10,sub);


    }






    public int operation(int a, int b, Add add) {
        return add.add(a, b);
    }

    interface Back {

        int back(); //返回固定参数

    }

    interface Add {
        int add(int a, int b); //返回值


    }

    interface Log {
        void log(String msg);
    }
}

3. Definition and use of high-order functions in kotlin

        Through the expression learning of Java's lambda, the use of expressions has been mastered. In kotlin, lambda expressions are defined as higher-order functions. almost the same usage

In kotlin, the definition of higher order functions:

Format: function name (parameter type...) -> return value

例如:add(Int ,Int)->Int,log(String)->Unit

Formal parameters only need to declare the parameter type, and can support multiple or empty. Return value, if you don't need to directly use Unit

tutorial

Kotlin's higher-order functions are similar to Java's lambda expressions, but they are used differently. Higher-order functions are used in functions and used as parameters. Similar to interface callback.

Actual combat:

1. Define an addition

 fun add(a: Int, b: Int, log: (Int, Int) -> Int) {

        val data = log(a, b)
        Log.log(data)

    }

2. call

    test.add(2, 3, { a, b ->
        Log.log("a + b=${a + b}")
        a + b
    })

    test.add(2, 4) { a, b ->

        a + b
    }

There are two normal calls:

1. The parameters are in the method body (2,3,{a,b->})

2. Outside the method (2,4){a,b->}

Note: If there is a return value, the expression or parameter in the last line will be returned as a function variable without using return

There are two types of calls by reference:

1. Defining a function in the function body is the same as the parameter function in the method, and implementing the method body of this function

    fun addNum(a: Int, b: Int): Int {

        return a + b

    }

transfer:

Just use the current function variable to refer to this method

   val addNum3 = test.add(1, 2, test::addNum)

2. Define a method outside the function body. Kotlin supports defining functions outside the function body. This function is similar to a global function, but the call only needs to point to the function name and does not need the current class.

    val addNum2 = test.add(1, 2, ::addNum)

Demo:

class Test {


    fun add(a: Int, b: Int, log: (Int, Int) -> Int) {

        val data = log(a, b)
        Log.log(data)

    }

    fun log(msg: String, show: (String) -> Unit) {
        show(msg)
    }

    fun addNum(a: Int, b: Int): Int {

        return a + b

    }

}

fun main() {
    val test = Test()
    test.add(2, 3, { a, b ->
        Log.log("a + b=${a + b}")
        a + b
    })

    test.add(2, 4) { a, b ->

        a + b
    }



    test.log("msg") {

        Log.log(it)

    }

    val addNum2 = test.add(1, 2, ::addNum)
    Log.log("addNum2=${addNum2}")

    val addNum3 = test.add(1, 2, test::addNum)
    Log.log("addNum3=${addNum3}")
}

// ::addNum 这是一种函数引用的写法,表示将函数addNum()来作为参数传递给高阶函数
fun addNum(a: Int, b: Int): Int {

    return a + b

}

Four. Summary

        Kotlin is written in a special way. Higher-order functions are similar to interface returns, and lambda expressions in Java are more like a definition language. But the grammatical interface is similar, but there are differences in usage.

        Especially kotlin, in the general trend of writing in kotlin, high-level functions are used a lot, and some developers even regard high-level functions as interface callbacks. Novices pay special attention.

Guess you like

Origin blog.csdn.net/qq36246172/article/details/131942578