Lambda expressions,

Source: Internet
Author: User

Lambda expressions,

Without knowing it, the year of July passed, that is to say, 1/6 has passed since the year of July. It is terrible to think about it again.

Continue todayKotlinLambda's history, definitions, and set function APIs, as well as recommendedWith andApply two common functions.

Lambda expressions

Lambda expressions are named after the lambda Algorithm in mathematics and directly correspond to the lambda abstraction action. They are an anonymous function, that is, a function without a function name. Lambda expressions can represent closures. InIn Java 8, lambda expressions are added to simplify code and facilitate developers to develop more efficient code.

The expression is simple:

 (argument) -> (body)

Lambda encodes a small piece of code that you can use as a value for passing. It can be declared independently and stored in a variable. But more often, it is declared directly when it is passed to a function. InIn KotlinLambda expressions are often surrounded by braces, as shown in the following code:

 val sum = { x: Int, y: Int -> x + y }

Java implementation may be as follows:

 int sum(int x,int y) { return x + y; }

To simplify the code,Lambda expressions are getting shorter and shorter. When we click a button, the corresponding view id is printed, as shown in the code below:

 btn?.setOnClickListener({ v -> print(v.id) }) 

WhenWhen a lambda expression is used as a parameter and is the last parameter in the parameter list, you can put {} out:

 btn?.setOnClickListener(){ v -> print(v.id) }

When lambda is the only parameter of a function, you can also delete the empty parentheses:

 btn?.setOnClickListener{ v -> print(v.id) }
Use Set of functional APIs

Function-style Code simplifies the code so that the Code is not separated by various logic. The Set also provides some common function-style APIs, making development more efficient.

Filter and map

I remember these two functions when I learned RxJava. They are similar in Kotlin. You can refer to RxJava to understand these two functions (filter and map ).

Val nums = listof (1, 4, 8, 9) list. filter {it % 2 = 0} // even

The printed result is

[2, 4]

In the filter, a boolean value is actually returned, and only the returned value is true. Of course, the returned value is still of the previous type (for example, the list returned in the example is still list)

val nums = listof(1, 2, 4, 5)list.map{ it *it } // 

The printed result is

[1, 4, 16, 25]
Prediction: all, any, count, and find

All returns true only when all conditions meet the specified conditions (predictions). If any, the system determines that at least one condition is met. find finds the first specified condition, and count indicates the number of elements that meet the prediction.

groupBy

Groups conditions of a specified dimension and groups the same elements of a specified dimension. The returned value is of the map type.

With and apply Functions
fun alphabet(): String { val result = StringBuilder() for (letter in 'A'..'Z') { result.append(letter) } result.append("\nNow I know the alphabet!") return result.toString()}

Because the code is widely usedResult, which is very troublesome to write.

Fun alphabet (): String {val stringBuilder = StringBuilder () return with (stringBuilder) {// 1 specify the receiver value in the method you call for (letter in 'A '.. 'Z') {this. append (letter) // 2 call the method of the receiver value through explicit "this"} append ("\ nNow I know the alphabet! ") // 3 call the method and ignore" this "this. toString () // 4 return values from lambda }}

This can be ignored. However, you can declare variables when you need to write this object of this class in alphabet.

Basically, apply is similar to:

Fun alphabet (): String {val stringBuilder = StringBuilder () return StringBuilder (). apply {// 1 specify the receiver value in the method you call for (letter in 'A '.. 'Z') {this. append (letter) // 2 call the method of the receiver value through explicit "this"} append ("\ nNow I know the alphabet! ") // 3 call the method, ignore" this "// 4 return value from lambda}. toString ()}

The difference between the two lies in the return value.StringBuilder's own type, while apply returns are stillStringBuilder type.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.