Java Lambda Expression Context








Lambda expressions can be used only in the following four contexts.

  • Assignment Context
  • Method Invocation Context
  • Return Context
  • Cast Context




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;//from   www.j  a  v a  2s .c o  m
    System.out.println(iCal.calculate(1, 2));
  }
}

@FunctionalInterface
interface Calculator{
  int calculate(int x, int y);
}

The code above generates the following result.





Method Invocation Context

We can use a lambda expression as an argument for a method or constructor.

public class Main {
  public static void main(String[] argv) {
    engine((x,y)-> x / y);//  www  .  j  a v a2s . co m
  }
  private static void engine(Calculator calculator){
    long x = 2, y = 4;
    long result = calculator.calculate(x,y);
    System.out.println(result);
  }  
}

@FunctionalInterface
interface Calculator{
  long calculate(long x, long y);
}

The code above generates the following result.

Return Context

We can use a lambda expression 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));
  }//  ww w .j  a v  a2s  .  com
  private static Calculator create(){
    return (x,y)-> x / y;
  }  
}

@FunctionalInterface
interface Calculator{
  long calculate(long x, long y);
}

The code above generates the following result.

Cast Context

We can use a lambda expression preceded by a cast. The type specified in the cast is its target type.

public class Main {
  public static void main(String[] argv) {
    engine((IntCalculator) ((x,y)-> x + y));
  }//from w  w  w .j ava  2  s . co  m
  private static void engine(IntCalculator calculator){
    int x = 2, y = 4;
    int result = calculator.calculate(x,y);
    System.out.println(result);
  }
  private static void engine(LongCalculator calculator){
    long x = 2, y = 4;
    long result = calculator.calculate(x,y);
    System.out.println(result);
  }  
}

@FunctionalInterface
interface IntCalculator{
  int calculate(int x, int y);
}

@FunctionalInterface
interface LongCalculator{
  long calculate(long x, long y);
}

The code above generates the following result.