kotlin lambda expression

1. Concept

Lambda expression in Kotlin is a concise syntax form used to represent an anonymous function . Lambda expressions can be passed as parameters in functions or assigned to a variable or constant .

2. Basic syntax:

{
    
     参数列表 -> 函数体 }

Among them, the parameter list is optional. If there are parameters, each parameter needs to be separated by a comma, and the function body is required and is used to define the operation of the function.

For example, the following lambda expression represents a function that accepts two integer arguments and returns their sum:

val sum = {
    
     a: Int, b: Int -> a + b }
// 参数类型可以从上下文中推断出来,则可以省略参数类型
// 下面的代码等价于上面的代码
val sum = {
    
     a, b -> a + b }

3. Implicit parameters:

If the lambda expression has only one parameter , and the type of that parameter can be inferred from the context, you can use the keywordit to refer to the parameter

val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenNumbers = numbers.filter {
    
     it % 2 == 0 }

In this example, filterthe function accepts a Lambda expression as argument and returns a new list containing all elements that satisfy the condition.

4. Trailing Lambda Expressions

In Kotlin, if the last parameter of a function is a function type , we can write the lambda expression inside curly braces outside the parentheses instead of passing the lambda expression inside the parentheses. This syntax is called "trailing lambda expression" or "final lambda expression".

For example:

// 最后一个参数 operation 是一个函数类型
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    
    
    return operation(a, b)
}

// 我们在调用的时候直接使用 {a,b -> a + b}
val sum = calculate(10, 20) {
    
     a, b -> a + b }
val difference = calculate(30, 15) {
    
     a, b -> a - b }

5. Expression returns result

You can use the return statement in a Lambda expression to return a result. However, if the lambda expression is defined inside a function, the return statement will return the result of the function, not the result of the lambda expression. If you want to return the result of a Lambda expression, you need to use a label to specify that the result of the Lambda expression is returned.

For example:

fun main() {
    
        
    val numbers = listOf(1, 2, 3, 4, 5)     
    val result = numbers.map {
    
            
        if (it == 3) return@map "three"        		            "number $it"    
    }
    // 打印的结果是[number 1, number 2, three, number 4, number 5]
    println(result)
}

Guess you like

Origin blog.csdn.net/flytosky21/article/details/130030489