Nemo_Sol Nemo_Sol - 1 month ago 15
Java Question

Lambda Expression without types

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);});
}

}

Answer

The lambda expression x -> { System.out.println(x); } can be expanded to

new Foo() {
    @Override
    public void bar(Object x) {
        System.out.println(x);
    }
}

When you call doo, you call 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");
}