Release Android Function Energy (I): Lambda expressions in the Kotlin language, kotlinlambda
Original article title: Unleash functional power on Android (I): Kotlin lambdas
Link: http://antonioleiva.com/operator-overloading-kotlin/
Antonio Leiva (http://antonioleiva.com/about)
Original article published:
Although Java 8 already contains some functional tools, Android Developers may not be able to use them immediately (or even not) as you think, but if they are used properly, functional programming is still a very powerful tool. So many other programming languages are starting to solve this problem.
Functional Programming in Modern Programming Languages
BecauseFunctional programming depends on functions and persistence.So function calls always return the same results. Generally, perfection is at a reasonable balance among all parties, so most modern programming languages, such as Kotlin or Scala, are in a single programming language,Integrated procedural programming and functional programming methodsAnd have the most advanced concepts in these two aspects. Some problems are more appropriate to be solved by functional programming, while some adopt procedural programming more directly.
Use the Kotlin language to implement Lamba expressions in Android
Lambda expressions are a simple way to define anonymous functions. Lambda expressions are very useful because Lambda expressions avoid writing explicit function declarations in abstract classes or interfaces and avoid class implementations. In the Kotlin language,A function can be used as a parameter of another function.. For example, you can simplify the callback function:
1 fun runAsync(callback: () -> Unit) {2 ...3 callback()4 }
This usage is quite clear. After some conversions are completed (as will be seen later), the function call method can be simplified:
1 runAsync { toast("Finished") }
Another outstanding aspect of the Kotlin language is the ability to write interfaces using lambda expressions, which can greatly simplify code. For example, it is easier to understand. Suppose you want to write the typical setOnClickListener () method of the view.
In Java, the interface code is similar to the following:
1 public interface OnClickListener {2 void onClick(View v);3 }
Then, you need to write an anonymous class to implement this interface:
1 view.setOnClickListener(new OnClickListener() {2 @Override3 public void onClick(View v) {4 Toast.makeText(v.getContext(), "Click", Toast.LENGTH_SHORT).show();5 }6 });
This code is converted to the Kotlin language (using Ankotoast
Function) will be like this:
1 view.setOnClickListener(object : OnClickListener {2 override fun onClick(v: View) {3 toast("Click")4 }5 })
As mentioned above, the Kotlin language allows some optimizations to Java language libraries, and any functions with interfaces can be replaced by functions. Run as defined by setOnclickListener:
1 fun setOnClickListener(listener: (View) -> Unit)
Lambda expressions are defined by parameters of the function on the left of the arrow (in parentheses) and return the value to the right of the arrow. In this exampleView
ReturnUnit
(No parameter ). The above code can be simplified as follows:
1 view.setOnClickListener({ view -> toast("Click")})
Wonderful difference! When defining a function, square brackets must be used on the left of the arrow and parameter values must be specified. The function Execution Code is on the right of the arrow. If no parameters are used on the left side, you can save the left side:
1 view.setOnClickListener({ toast("Click") })
If the last parameter of a function is a function, you can move the function as a parameter out of parentheses:
1 view.setOnClickListener() { toast("Click") }
Finally, if the function is a unique parameter, you can remove the parentheses:
1 view.setOnClickListener { toast("Click") }
Compared with the initial Java language code, the amount of code is less than 1/5 of the original, and it is easier to understand. This is really impressive. Anko provides a simplified version (essentially called the function name), which consists of the extension functions of the implementation methods shown earlier:
1 view.onClick { toast("Click") }
Extended Programming Language
Thanks to these transformations, you can create your own builder and code block. The standard library of the Kotlin language provides functions that are as interesting as. The following is a simpler implementation method:
1 inline fun <T> with(t: T, body: T.() -> Unit) { t.body() }
This function obtains an object of type T and A function used as an extension function. The implementation process only solves objects and allows objects to execute functions. Because the second parameter of the function is another function, you can move it out of brackets. In this way, you can directly usethis
Keyword Creation
Code block, you can also directly use the public attributes and functions of the object:
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 you haven't used functional programming methods, you need a lot of practices. This is worthwhile. If you want to learn more about lambda expressions and Kotlin, you can get it from my book.