This section discusses Kotlin’s Lambda closure, its declarations, and how it works

Lambda closure

Let’s start with a very common example of creating a child thread in Java:

We know that Java 8 also has Lambda support, which can omit Runnable objects into a () -> representation.

Next, let’s look at Kotlin’s Lambda form, which is similar to Java 8 Lambda, except that -> is placed inside {}.

Kotlin’s Lambda syntax also has many features that allow you to omit a lot of information that you don’t have.

For example, if your Lambda has no arguments, you can omit the -> symbol. In the example, Runnable takes no parameters and can be written as follows:

Next, if Lambda is the last argument to the function, you can place the curly brace outside the curly brace;

If the function has only one argument and the argument is Lambda, you can omit the parentheses.

This is the simplest structure in Kotlin Lambda:

Lambda closure declaration

Let’s look at how a closure is written when declared separately:

Closures can also have parameters. Parameter declarations are basically the same as variable declarations. Variable names: variable type -> Lambda closure body.

As you can see from the examples, closure calls come in two forms, one directly using parentheses to add arguments, and the other by calling its invoke method.

Lambda closure principle

First, write a closure that takes one argument:

Let’s take a look at the corresponding Java source code:

As you can see from the converted Java code, the closure we wrote is converted to a class for Function1, which is actually an interface in the Kotlin library. We open functions.kt file: functions.kt

If you look at the end, you’ll see that there are 23 interfaces in total, from Function0 to Function22. You can see that the number following the interface name represents the number of arguments the closure can accept. In the above example, we passed in an Int argument, So the Function1 interface is used. Can only accept closures with fewer than 22 parameters? Let’s look at another example:

We declare a closure with 23 parameters, and then look at the Java source code:

You’ll find that it cleverly solves the problem of 22 + arguments using arrays as arguments using the FunctionN interface.

Ok, let me take a look at this functionn.kt file:

It should be noted that closures with 22 parameters were indeed supported prior to Kotlin 1.3, and N parameters were supported after 1.3.

That is the content of this section, welcome to pay attention to ~