Kotlin Learning and Practice (ix) Lambda and Java functional interfaces with receivers

Source: Internet
Author: User
Tags java anonymous class

Lambda with receiver
* A method in the body of a lambda function that can invoke a different object without any additional qualifiers, which is not found in Java.
* Such lambda is called "Lambda with receiver"

Let's start with a normal function as a counter-example:
Fun Alphabet (): String {    val result = StringBuilder () for (letter in    ' A ' ... ') Z ') {        result.append (letter)    }    result.append ("\nnow, I know the alphabet")    return result.tostring ()}

In the above example, you can see the function of the result object repeated calls, if repeated calls will become very bad, Kotlin with the recipient of the lambda to solve the problem.

First look at the wtih function:

* With  syntax is a function that receives two parameters: strict write should be with (Aa,{...lambda ...}), using the Convention that the lambda as the last parameter can be placed outside the parentheses can improve readability with  (xx) {... Lambda ...}
* The WITH function converts the first parameter to the recipient of the lambda that is the second parameter, which can be explicitly accessed by this reference, or it can be omitted to directly access the
Fun Alphabetwith (): String {    val result = StringBuilder ()    return with (result) {        ///Specify the recipient's value, then you can use the C6/>for (letter in ' A ' ... ') Z ') {            this.append (letter)///via this display to call the recipient        }        append ("\nnow, I know the Alphabet")//can also omit this to invoke the receiver        result.append ("hahaha")        this.tostring ()//return from Lambda    }}
* You can use the expression function body syntax to continue simplifying functions.
Fun ALPABETWITHF () = with (StringBuilder ()) {for (letter in    ' A ' ... ') Z ') {        this.append (letter)///via this display to call the recipient    }    append ("\nnow, I know the Alphabet")//can also omit this to invoke the receiver    Append ("hahaha")    toString ()//return from Lambda}
* The with return value is the result of executing the lambda code, and the result is the value of the last expression in the lambda.
* The Apply function comes in handy if you want to return the recipient object (the object that passed into the lambda) rather than the result of the lambda execution.

* Apply is declared as an extension function. Its recipient becomes the recipient of the lambda as the argument.
* The result of executing apply is StringBuilder, so you can then call ToString to convert it to a string.
Fun alpabetapply () = StringBuilder (). Apply {to (letter in    ' A ' ... ') Z ') {        this.append (letter)///via this display to call the recipient    }    append ("\nnow, I know the Alphabet")//can also omit this to invoke the receiver    Append ("hahaha")}.tostring ()
* Kotlin can use apply on any object, no special support is required.
* Apply allows you to use the style of compact expression function body
* After Lambda executes, apply returns the instance of the receiver that has already been initialized
Fun Createviewwithcustomattribites (Context:context) = TextView (context). Apply{text = "simple text" testsize = 20setPadding (20,15,1,0)}

These are the most typical and basic lambda functions in Kotlin, with the exception of with apply and other well-used function with the recipient ....

A functional interface using Java
* In Kotlin you can pass a lambda instead of a traditional anonymous class in Java to do the argument
* The way you can work with Lambda instead of a Java anonymous class is because there is only one abstract method in the ActionListener interface. (Runnable, callable)
* This interface is called a functional interface, or Sam interface, and the SAM represents a single abstract method.
* Kotlin allows you to use lambda when you call the Receive function interface as a parameter, to keep your code tidy.
Fun Lambdainnerclass () {//    val btn = button ()//    btn.setonclicklistener{v-> println ("")}    val btn = button ()    Btn.addactionlistener {e-println ("Hahaha")}}

Here is an example of a demo that first releases the Java-defined function:

public class Javacalltest {public      void postponecomputation (int delay, Runnable computation) {        thread thread = new Thread (computation);        try {            thread.join (delay);            Thread.Start ();        } catch (Interruptedexception e) {            e.printstacktrace ();}}    }
* Using lambda instead of anonymous class parameters in Koltin, the compiler translates the final lambda auto-compilation into a runnable instance passed to the method
Val javatest = Javacalltest () fun Testlambdacalljava () {    javatest.postponecomputation (+) {        println (    $) }     //The following shows that creating an anonymous object can also achieve    the effect Javatest.postponecomputation (object:runnable {        override Fun Run () {            println ("452")        }    )}
* Here's a little different, when you explicitly declare an object, each call creates a new object.
* Using lambda is different: if the lambda does not have access to any of the variables that define it, the anonymous class object of the response can be reused between multiple invocations.
Val runnable = runnable {println)}fun reusing () {    javatest.postponecomputation (+ runnable)}
* The above runnable uses lambda to generate objects that are reused multiple times because there are no variables defined in the reference function
* If a lambda captures a variable from its bounding scope, each invocation can no longer reuse the same instance, creating a new object each time that stores the value of the captured variable
Following
Fun Handlecomputation (id:string) {    javatest.postponecomputation (+) {        println (ID)    }}
Sam interfaces have some other features that are not listed for the time being ...

Kotlin Learning and Practice (ix) Lambda and Java functional interfaces with receivers

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.