Reputation: 682
Handler handler = new Handler(Looper.getMainLooper() );
Runnable workRunnable;
@Override public void afterTextChanged(Editable s) {
handler.removeCallbacks(workRunnable);
workRunnable = () -> search(s.toString());
handler.postDelayed(workRunnable, 500 /*delay*/);
}
what does this expression mean?
workRunnable = () -> search(s.toString());
In normal Java code how is it written in?
Upvotes: 0
Views: 113
Reputation: 34470
Doing this:
workRunnable = () -> search(s.toString());
is the same as doing:
workRunnable = new Runnable() {
@Override
public void run() {
search(s.toString());
}
};
Actually, low-level implementation is different and lambdas aren't just syntactic sugar added by the compiler, i.e. they are not internally translated to anonymous inner classes. Nevertheless, when anonymous inner classes extend a functional interface (an interface that has only one abstract method), both mean almost the same, from a semantic point of view.
One difference is that within an anonymous inner class, if you refer to this
, you will be referencing the instance of the anonymous inner class, while within a lambda, if you refer to this
, you will be referencing the instance of the enclosing class where the lambda is defined.
You might want to read the lesson about lambdas in The Java Tutorial, which explains lambdas and how to use them.
Upvotes: 2
Reputation: 4805
Lambdas are anonymous implementations of single method interfaces. They can be any single method interface, but built-in ones include:
() -> doSomethingButDonTReturnAnything() // Runnable
() -> returnV() // Supplier<V>
x -> doSomethingWithXButDontRetunAnything(x) // Consumer<K>
x -> returnVFromX(x) // Function<K,V>
(x, y) -> doSomethingWithXAndYButDontReturnAnything(x,y) // BiConsumer<K,V>
(x, y) -> doSomethingWithXAndYAndReturnM(x, y) // BiFunction<K,V,M>
() just means there are no input parameters. There are also Primitive versions like IntFunction and Predicate. Any code that implements the required interface can be used inside the lambda, i.e. Function for Stream::map can be anything that takes K and returns V. One limitation is that the built-in interfaces don't throw exceptions, so you have to roll your own interfaces if you want to use lambdas that throw exceptions.
Upvotes: 0