Reputation: 352
I understand the syntax of the Java8 lambda expressions but why does the following code work without a specific type declaration of x? Why is "baz" being printed?
public class LambdaExpressions {
interface Foo {
void bar(Object o);
}
static void doo(Foo f) {
f.bar("baz");
}
public static void main(String[] args) {
doo( x -> {System.out.println(x);});
}
}
Upvotes: 6
Views: 1934
Reputation: 191738
Since the interface is a standard functional interface
It's a functional interface because it contains only one abstract method. This method takes one parameter and returns a [void] value
(Reworded for this question)
The lambda expression x -> { System.out.println(x); }
can be re-written as an anonymous class.
new Foo() {
@Override
public void bar(Object x) {
System.out.println(x);
}
}
When you call doo
, you pass this functional interface as f
, which then executes f.bar("baz");
, so "baz"
is x
, and it is printed.
All in one main method, this would look like
public static void main(String[] args) {
Foo f = new Foo() {
@Override
public void bar(Object x) {
System.out.println(x);
}
};
f.bar("baz");
}
Upvotes: 7
Reputation: 72854
The type of the parameter x
is inferred as per the specification:
The formal parameters of a lambda expression may have either declared types or inferred types. These styles cannot be mixed: it is not possible for a lambda expression to declare the types of some of its parameters but leave others to be inferred. Only parameters with declared types can have modifiers.
In this case, the compiler infers the type to be Object
since the method accepts a functional interface with a method accepting an Object
. Also mentioned in that section of the spec:
If the formal parameters have inferred types, then these types are derived (§15.27.3) from the functional interface type targeted by the lambda expression.
Upvotes: 5
Reputation: 1320
Essentially it is because Foo is a standard functional interface.
A standard functional interface contains one (and only one) abstract function. Java 8 allows for lambdas to stand in place of creating an instance of the interface for a shorter and cleaner notation.
Upvotes: 1