Lambda expressions can be used only in the following four contexts.
* Assignment Context: A lambda expression can appear to the right of the assignment operator.
```
public class Main {
public static void main(String[] argv) {
Calculator iCal = (x,y)-> x + y;
System.out.println(iCal.calculate(1, 2));
}
}
@FunctionalInterface
interface Calculator{
int calculate(int x, int y);
}
```
* Method Invocation Context: a lambda expression can used as an argument for a method or constructor.
```
public class Main {
public static void main(String[] argv) {
engine((x,y)-> x / y);
}
private static void engine(Calculator calc){
long x = 2, y = 4;
long result = calc.calculate(x,y);
System.out.println(result);
}
}
@FunctionalInterface
interface Calculator{
long calculate(long x, long y);
}
```
* Return Context: a lambda expression can used in a return statement, and its target type is declared in the method return type.
```
public class Main {
public static void main(String[] argv) {
System.out.println(create().calculate(2, 2));
}
private static Calculator create(){
return (x,y)-> x / y;
}
}
@FunctionalInterface
interface Calculator{
long calculate(long x, long y);
}
```
* Cast Context: a lambda expression can preceded by a cast. The type specified in the cast is its target type
```
public class Main {
public static void main(String[] argv) {
engine((Calculator) ((x,y)-> x + y));
}
private static void engine(Calculator calc){
int x = 2, y = 4;
int result = calc.calculate(x,y);
System.out.println(result);
}
}
@FunctionalInterface
interface Calculator{
int calculate(int x, int y);
}
```