More on Lambdas

This lesson continues discussion on lambdas in Java.

We'll cover the following...

Question # 1

Can lambda be thought of as replacement of anonymous classes for implementing functional interfaces?

No, one primary difference between the two is that the anonymous classes can maintain state as they can have instance or static variables whereas lambda expressions are just method implementations.

Question # 2

In the below example, why do we not need to specify the type of the parameters being passed in to the lambda expression?

interface CrunchNumbers {

    void work(int a, int b);

}

void test() {

    // k and j don't have their types defined.
    myMethod((k, j) -> {
        System.out.println(k % j == 0 ? "exactly divisible" : "not divisible");
    });

}

We can skip specifying the types of the variables being passed into the method being implemented by the lambda expression because the compiler is intelligent enough to infer the types looking at the interface definition. This is called type inference. ...