1. What is Lambda expression?
- One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear.
- If interface contains only one method, then also we need to mention the method name in anonymous class declaration.
interface Runnable {
public void run();
}
Runnable runnable = new Runnable() {
public void run() {
System.out.println(“i am a new thread”);
}
};
|
- In above example, i am creating an implementation class (anonymous class) of Runnable interface, but still i need to mention method name ‘run()’.
- In this case by using lambda expression, we can directly pass functionality as an argument to another method to treat functionality as method argument, or code as data.
interface Runnable {
public void run();
}
Runnable runnable = () -> System.out.println(“i am a new thread”);
|
- We can use lambda expression, if the interface contains only one method.
- A lambda expression can be passed around as if it was an object and executed on demand.
2. Syntaxes of Lambda expressions
- Lambda expressions supports interfaces only, Creating an instance to implementation class of a functional interface (interface contains only one method).
- Suppose java.lang.Runnable interface is a functional interface, it contains only one method called ‘run()’.
- We can assign a block of code or method without a name to variable of type interface directly by using lambda expressions.
Runnable runnable = () -> {
System.out.println(“i am a new thread”);
};
|
- Block of code contains syntax like this :
(arguments list) -> { block of code }; - In lambda expression, no need to mention the name of the block.
- We can pass the list of arguments with or without data type mentioning.
- But recommended way is don’t mention data type, java compiler will detect the data type of the argument by looking into the functional interface.
- Suppose if we mention wrong data type (other than data type declared in interface method) it will give compile time error.
- It will also not consider inheritance relationship also, we need to mention exact type, not child type or not parent type, otherwise don’t mention any type it will add type.
- Java compiler automatically detects argument types and return type of the lambda expression.
- No need to mention the return statement also, by default it returns last statement.
- If you write last statement as improper, it gives compile time error.
- If you want we can also mention return statement, but it is optional to mention, but if you mention return statement need to write ‘{ }‘ code only.
- If block contains only one line of code than optional to use ‘{‘.
No comments:
Post a Comment