Lambda expressions 1. Basics

It is possible to talk about lambda expressions only after defining a functional interface, which is an interface with only one abstract method (see more details here). That is because a lambda expression is just the body of the implementation of a functional interface. Because such an interface has one abstract method only, the compiler knows exactly the signature of the method, so we can omit method name and provide only the body of the method implementation.

For example, here is a functional interface:

interface FirstExample {
     int addTwo(int n);
}

And here is a method that expects an object of this interface:

public double someMethod(FirstExample fe, double d){
      int x = fe.addTwo(3);
      return d * x;
}

If we can run this method without any lambda expression by implementing the FirstExample interface:

public class FirstExampleImpl implements FirstExample {
      public int addTwo(int n){
          return n + 2;
      }
}

If we call now the method as follows

double d = someMethod(new FirstExampleImpl(), 2.0)

the result (d value) is going to be 10.0. I hope it is obvious: (3 + 2) * 2.0.

Lambda expression allows simplifying an interface implementation. Instead of creating class FirstExampleImpl, we could just call the method someMethod() as follows:

double d = someMethod(x -> x + 2, 2.0);

The result will be exactly the same. The syntax of a lambda expression is follows:

– parameters inside the parentheses “( )” (can be omitted for a single parameter, as in our example);

– an arrow token “->” that separates parameters declaration form the method body;

– the method body inside the braces “{ }” (can be omitted if the method consists only of one statement, as in our example).

, , , ,

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes