Friday, 21 September 2018



                                            FunctionalInterface Vs Lambda Expressions:

Once we write Lambda expressions to invoke it’s functionality, then FunctionalInterface is required. We can use FunctionalInterface reference to refer Lambda Expression.Where ever FunctionalInterface concept is applicable there we can use Lambda Expressions




                                          
                                             Anonymous inner classes vs Lambda Expressions

Wherever we are using anonymous inner classes there may be a chance of using Lambda expression to reduce length of the code and to resolve complexity.


                                         What are the advantages of Lambda expression?

We can reduce length of the code so that readability of the code will be improved.

We can resolve complexity of anonymous inner classes.

We can provide Lambda expression in the place of object.

We can pass lambda expression as argument to methods.
Note:
1. Anonymous inner class can extend concrete class, can extend abstract class,can implement interface with any number of methods but Lambda expression can implement an interface with only single abstract method(FunctionalInterface).

2. Hence if anonymous inner class implements functionalinterface in that particular case only we can replace with lambda expressions.hence wherever anonymous inner class concept is there,it may not possible to replace with Lambda expressions.

3. Anonymous inner class! = Lambda Expression

4. Inside anonymous inner class we can declare instance variables.Inside lambda expression we can’t declare instance variables. Whatever the variables declare inside lambda expression are simply acts as local variables.

5. Inside anonymous inner class “this” always refers current inner class object(anonymous inner class) but not related outer class object.Within lambda expression ‘this” keyword represents current outer class object reference (that is current enclosing class reference in which we declare lambda expression)


Example:






From lambda expression we can access enclosing class variables and enclosing method variables directly.

The local variables referenced from lambda expression are implicitly final and hence we can’t perform re-assignment for those local variables otherwise we get compile time error



No comments:

Post a Comment