Lambda expression contexts

Description

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 ww w . j  a va2s  . co 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 .jav a  2s  .  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));
  }/*from w ww .j  a va  2  s  .c  o  m*/
  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));
  }// w  w w .j  av a2s. 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.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial