Wednesday, February 14, 2018

Lambda Expression

Lambda calculus is a big change in mathematical world which has been introduced in 1930. Because of benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first programming which uses Lambda Expression.

The other language which uses lambda expressions are:
o C#.Net
      o C Objective
      o C
      o C++
      o Python
      o Ruby etc.
      o and finally in java also.
The main objective of Lambda Expression is to bring benefits of functional programming into java.

What is Lambda Expression

Lambda Expression is just an anonymous(nameless) function. That means the function which doesn’t have the name, return type and access modifiers.Lambda Expression also known as anonymous functions or closures.

Ex:1
public void m1() {
         sop(“hello”);
  }
Ex:2
public void add(int a, int b) {
     sop(a+b);
  }

If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.
The above Lambda expression we can rewrite as
a, b –> sop(a+b);

Ex:3
public String str(String str) {
          return str;
   }
Conclusions

A lambda expression can have zero or more number of parameters(arguments).
Ex:
() –> sop(“hello”);
    (int a) –> sop(a);
    (int a, int b) –> return a+b; 
Usually we can specify type of parameter. If the compiler except the type based on the context then we remove type. i.e., programmer is not required.
Ex:
(int a, int b) –> sop(a+b);
    (a,b) –> sop(a+b); 
If multiple parameters present then these parameters should be separated with comma(,).
If zero number of parameters available then we have to use empty parameter [ like () ].

Ex:
() –> sop(“hello”); 
If only one parameter is available and if the compiler can expect the type then we can remove the type and parenthesis also.
Ex:
(int a) –> sop(a);
          (a) –> sop();
          A –> sop(a); 
Similar to method body lambda expression body also can contain multiple statements. If more than one statements present then have to enclose inside within curly braces. If one statement present then curly braces are optional.Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required.

No comments: