Lambda is the 11th Greek letter, uppercase λ, lowercase λ, amount, digress ... Lambda expressions are one of the new features of JAVA8:
- Lambda expression
- Function-Type interface
- Streaming API
- Default method
- The new date
- Time API
The lambda expression replaces the anonymous class, cancels the template, and allows code to be written in functional style.
Because recently contacted Rxjava, met the lambda, immediately likes on ~ so has studied.
This article focuses on the partial use of the lambda alternative to anonymous classes in Android.
Using Lambda in Android
Gradle-retrolambda
A Gradle plugin for getting Java lambda Support in Java 6, 7 and Android
In Android we need to use this plugin and configure it as configured.
Actual use
Since lambda can replace anonymous classes, we first pick a few anonymous classes to practice practicing.
Here is a simple mention of the syntax of the Lambda: ()-> {} What kind of ghost do you think I can see?
No hurry, look at a few examples first ~
Set up a listener event
In Android we set up the listener to write this:
Mfab.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (View v) {
dosomething ();
}
});
So writing as will prompt that the anonymous class new View.onclicklistener () can be replaced by a lambda:
Tips
So how can you write with a lambda?
Mfab.setonclicklistener (V->dosomething ());
Did you see that?
The entire anonymous inner class is replaced by V->dosomething ().
Is it very simple?
Ps: The ' V ' in this example represents the parameter V of the onclick Pass, and the parameters cannot be omitted, but can be named arbitrarily.
Implement Runnable
In Android we have a thread that usually writes:
New Thread (New Runnable () {
@Override public
void Run () {
dosomething ();
}
}). Start ();
and using lambda expressions, you can write this:
New Thread (()-> dosomething ()). Start ();
Alternatively, instantiating runnable member variables can be written like this:
Runnable Runnable = ()->dosomething ();
Have you seen the two examples that are interested in lambda? Follow-up I will continue to study, interested please continue to focus on ~