All About Lambdas

Functional programming with Lambdas
Lambdas were a part of the JDK Version 8 and enabled functional programming in Java, rather than simply object oriented programming.

What is a Lambda Function?

Java lambdas are functions which can be written independent of a class. They are methods that do not need to belong to a class to function. 

Benefits of Lambda Functions

  • Eliminates lengthy codes and allows concise coding
  • Enables functional programming, as opposed to object-oriented programming
  • Supports parallel processing

Functional Programming VS. Object-Oriented Programming

  • Lambdas allow more elegant and concise coding, without the need to use function names and access modifiers
  • Logic cannot exist in isolation in OO programming, but is possible in functional programming. 
In essence, lambdas allow the developer to assign a block of code to a value.

Lambdas generally follow the below pattern;

nameOfLambda = (Arguments) -> {CODE;};

Let us look at the following example;

public int sumOfNumbers (int a, int b){
         return a+b;
      } 

This is how a method to add two numbers would look in OO programming.

The same method can be written as follows in lambda functions;

sumOfNumbers = (int a, int b) -> {return a+b;}; 
 
(Lambda expression do require a type and the above is given simply as an example)

As you can see, lambda functions greatly simplify the code.

When writing a lambda function, it is not necessary to add an access modifier or a return type. It is intelligent enough to decipher the return type by considering the return and input values.

Lambda Expression Types

In order to render a data type to a lambda expression, an interface should be declared with the return type necessary for the lambda function.

For example;

interface myLambda {
   int addition();
Thereafter, it is possible to use myLambda data type for the lambda function. 

The above lambda function could be written as follows;

myLambda sumOfNumbers = (int a, int b) -> return a+b;
 
The signature of the lambda should match the signature of the interface.

Further, the interface that is declared should have only one method, so as not to confuse the lambda function. 





Comments

Popular Posts