Kotlin’s built-in extension function
This article is my Kotlin in the process of sorting out some knowledge points, if there is any mistake, welcome to correct
1, let
Example code is as follows:
obj.let { obj2 ->
// Business logic
}
Copy the code
Passing the original call object as an argument to a Lambda expression works with? The. Operator performs auxiliary null-processing
2, with
With takes two arguments. The first argument can be an object of any type and the second argument is a Lambda expression. The with function provides the context of the first argument object in the Lambda expression and returns the last line of the Lambda expression as the return value, as shown in the following example:
val result = with(obj) {
// where obj is the context
"value" // The last line of the with function returns the value
}
Copy the code
Multiple methods of the same object can be called consecutively
3, run
Similar to the with function, the run function cannot be used directly. Instead, it must call the run function of an object. The run function takes only a Lambda argument and provides the context for calling the object in the **Lambda ** expression. The last line of the Lambda expression is used as the return value, as shown in the following example:
val result = obj.run{
// where obj is the context
"value" // The last line of the with function returns the value
}
Copy the code
4, apply
Much like the run function, it needs to be called on an object, takes only a Lambda argument, and provides the context of the calling object in the Lambda expression. The apply function cannot specify a return value. Instead, it automatically returns the calling object itself.
val result = obj.apply{
// where obj is the context
}
// result == obj
Copy the code
5, repeat
Repeat receives two arguments, the first of which is an argument of type Int that specifies the number of cycles. The second argument is a Lambda expression. Repeat can repeat the Lambda expression within it as many times as specified. The following is an example:
repeat(4) { it ->
println(" it = $it")}// Run the result
it = 0
it = 1
it = 2
it = 3
Copy the code
More articles: Kotlin learning article based on knowledge points finish – – 01 Kotlin article based on knowledge points finish – – 02 Kotlin article based on knowledge points finish – – 03 Kotlin learning knowledge organizing – advanced – 04
In the last day of rebirth I feel ashamed now that I tried to take my life. It is such a precious thing. I had no one to talk me out of my despair, and that was a mistake. You need to keep people close. You need to give them access to your heart. I had tried to take my own life, and I was ashamed of it. Life is precious. I didn’t talk to anyone about my despair, and that was wrong. You need to be close to people. You need to let them be close to your heart.