Java - Intersection Type and Lambda Expressions


Java 8 introduced a new type called an intersection type.

An intersection type may appear as the target type in a cast.

An ampersand is used between two types, such as (Type1 & Type2 & Type3), represents a new type that is an intersection of Type1, Type2, and Type3.

The following code uses a cast with an intersection type that creates a new synthetic type that is a subtype of all types.

interface Sensitive {
  // It is a marker interface. So, no methods exist.

interface Adder {
  int add(int a, int b);

public class Main {
  public static void main(String[] args) {
    Sensitive sen = (Sensitive & Adder) (x, y) -> x + y; // OK

The intersection type Sensitive & Adder is still a functional interface.

The target type of the lambda expression is a functional interface with one method from the Adder interface.

To make a lambda expression serializable, use a cast with an intersection type.

The following statement assigns a lambda expression to a variable of the Serializable interface:

Serializable ser = (Serializable & Adder) (x, y) -> x + y;