Wednesday, April 8, 2020

Lambda expressions

Hello,

As you know, functional programming is based on the use of lambda expressions at the code level. lambda expressions are also called closures or anonymous functions: their main purpose is to allow a set of treatments to be passed as parameters. In addition, functional programming has become predominant in recent languages.

In this programming mode, the result of treatments is described but not the way in which they are carried out. This reduces the amount of code to write to achieve the same result.

In java for example to declare a method with a loop we follow the following procedure:

for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}

Using lambda expressions The code of the loop could be factored in a method which would wait as a parameter for a function which contains the processing to be performed on each element.

list.forEach(System.out::println);

So we can say that a lambda expression is therefore a syntactic shortcut that simplifies the writing of treatments passed as parameters. It is particularly useful especially when the processing is useful only once: it avoids having to write a method in a class. Another definition is that the lambda expression allows to encapsulate a processing to be moved on to other treatments. It is a syntactic shortcut to internal anonymous classes for an interface that has only one abstract method. This type of interface is called a functional interface.

Below is a small example to show how we can declare a function with a chosen return type.


you can consult the article in french, Lambda Expressions

0 comments:

Post a Comment