TL;DR: A lambda expression is a shortcut notation to anonymous inner classes containing a single method. Usually, they define implementations for functional interfaces (interfaces declaring a single method).
Today I finally found out what lambda expressions are (formally) by watching this tutorial.
Lambda expressions are a concise way of passing pieces of code around. You can look at lambda expressions as shorthand for anonymous inner classes.
There is a catch though: They are valid for functional interfaces.
Functional interfaces
Functional interfaces are interfaces defining a single method, like this:
interface IFunctional {
void method1();
}
Following interface is not functional, hence it can't be used in lambdas:
interface INonFunctional {
void method1();
void method2();
}
Lambdas
Anonymous inner classes are inline implementations of e.g. interfaces. I.e. instead of defining a full object, creating and using it, you do it on the fly. If it just implements a functional interface, you can use lambda expression. Here's an example:
Assuming you have the interface:
interface Operation {
int op(int a, int b);
}
and a class:
class Executor {
// Just execute the operation and log its result
//
public void execute(Operation operation) {
int result = operation.op(20, 10);
Log.d("Result of operation is: " + result);
}
}
We want to define some code for the Operation and execute() it:
Executor = new Executor();
Now, we can define the Operation via anonymous inner class:
executor.execute(new Operation() {
// an addition operation
int op(int a, int b) {
return a + b;
}
}
It will print 30 , which is 20 + 10.
We can also use lambda expressions (remember the functional interface thing?):
executor.execute(
(int a, int b) -> a + b
);
The result will be the same. Much shorter, no?
We can go even further (since the interface is not ambiguous) and remove the types:
executor.execute(
(a, b) -> a + b
);
TADA! Now you can see it fits with the anti-boilerplate trend in android development.
HTH,
Member discussion: