Free Android's functional Energy (I): lambda expression for Kotlin language

Source: Internet
Author: User

Original title: Unleash Functional Power on Android (I): Kotlin lambdas

Original link:http://antonioleiva.com/operator-overloading-kotlin/

Original Antonio Leiva (http://antonioleiva.com/about/)

Published in the original: 2015-08-05

While Java 8 already contains some functional tools, and as you might imagine, Android developers are not able to use these tools immediately (and perhaps not at all), functional programming is still a powerful tool if used properly. For this reason many other programming languages are beginning to solve this problem.

functional programming in modern programming languages

Because functional programming relies on functions and permanence , function calls always return the same result. In general, perfection is at a reasonable equilibrium point, so most modern programming languages, such as Kotlin or Scala, are in a single programming language, fusing procedural programming and functional programming methods , and have the most advanced concepts in both. Some problems are more appropriate with functional programming, while some follow procedural programming more directly.

in theAndroidin useKotlinLanguage ImplementationLambaAn expression

A lambda expression is an easy way to define an anonymous function. This is useful because lambda expressions avoid writing explicit function declarations in abstract classes or interfaces, which in turn avoids the implementation part of the class. In the Kotlin language, you can use one function as an argument to another function . For example, a function that requires a callback (callback) can be simplified to:

1 Fun RunAsync (callback: (), Unit) {2    ... 3     Callback ()4 }

This usage is quite clear. After completing some transformations (as you'll see later), the way the function is called can be simplified:

1 RunAsync {toast ("finished")}

Another great aspect of the Kotlin language is that it allows the interface to be written with lambda expressions, which can greatly simplify the code. For example, it is easier to understand, assuming a typical Setonclicklistener () method to write a view.

In the Java language, the interface code looks like this:

1  Public Interface Onclicklistener {2void  OnClick (View v); 3 }   

Then, you need to write an anonymous class to implement this interface:

1 view.setonclicklistener (new  Onclicklistener () {2@Override3  publicvoid  OnClick (View v) {4 toast.maketext (V.getcontext (), "click", Toast.length_short). Show (); 5 }6 });         

This code translates to the Kotlin language (with the Anko toast function):

1 View.setonclicklistener (Object:onclicklistener {2override fun OnClick (V:view) {3 Toast ("click")4}5 })      

As mentioned earlier, theKotlin language allows some optimizations to the Java language Class library, and any function with an interface can be replaced by a function. Run as you would define the Setonclicklistener () method:

1 Fun Setonclicklistener (listener: (View), Unit)

The lambda expression is defined by the arguments to the left function of the arrow (the contents in parentheses) and returns the value to the right of the arrow. In this example, the resulting View return is given Unit (no arguments ). According to this idea, the above code can be simplified slightly:

1 view.setonclicklistener ({view, Toast ("click")})

Wonderful difference! When defining a function, you must use square brackets to the left of the arrow and specify the value of the parameter, and the execution code of the function is to the right of the arrow. If you don't use parameters on the left, you can even omit the left part:

1 view.setonclicklistener ({Toast ("click")})

If the last parameter of the function is a function, you can move the function as a parameter outside the parentheses:

1 view.setonclicklistener () {Toast ("click")}

Finally, if the function is a unique parameter, you can also remove the parentheses:

1 View.setonclicklistener {toast ("click")}

Compared to the initial Java language Code, the code amount is less than one-fifth and easier to understand. This is indeed impressive. Anko to a simplified version (essentially a function name), consisting of an extension function of the implementation method shown previously:

1 View.onclick {toast ("click")}

Extended programming language

Thanks to these transformations, you can create your own generator (builder) and block of code. the Kotlin language standard library provides some interesting functions like with. Here's a simpler way to implement it:

1 inline fun <T> with (T:t, Body:t. (), Unit) {t.body ()}

This function gets an object of type T and the function used as an extension function. The implementation process only solves the object and lets the object execute the function. Because the second argument of a function is another function, you can move it outside the brackets. This allows you to use the object's this 关键字创建 block of code directly, as well as to work directly with the object's public properties and functions:

1 With (forecast) {2    picasso.with (itemview.ctx). Load (ICONURL). into (IconView)3      dateview.text = date4     descriptionview.text = description5     Maxtemperatureview.text = "${high.tostring ()}º"6     mintemperatureview.text = "${low.tostring () }º "7    itemview.onclick {itemclick (forecast)}8 }

Summary

The energy of lambda expressions lies in our imagination. If the functional programming method is not used, a lot of practice is needed, and it is worthwhile to do so. If you want to learn more about lambda expressions and Kotlin-related content, you can write from my the book obtained in the .

Free Android's functional Energy (I): lambda expression for Kotlin language

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.