Java Reference
In-Depth Information
public static void printMapping(Object[] from, int[] to) {
for(int i = 0; i < from.length; i++) {
System.out.println(from[i] + " mapped to " + to[i]);
}
}
}
Mapping names to their lengths:
David mapped to 5
Li mapped to 2
Doug mapped to 4
Mapping integers to their squares:
7 mapped to 49
3 mapped to 9
67 mapped to 4489
Intersection Type and Lambda Expressions
Java 8 introduced a new type called an intersection type that is an intersection (or subtype) of multiple types. 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 . Consider a marker interface
called Sensitive , shown in Listing 5-10.
Listing 5-10. A Marker Interface Named Sensitive
// Sensitive.java
package com.jdojo.lambda;
public interface Sensitive {
// It ia a marker interface. So, no methods exist.
}
Suppose you have a lambda expression assigned to a variable of the Sensitive type.
Sensitive sen = (x, y) -> x + y; // A compile-time error
This statement does not compile. The target type of a lambda expression must be a functional interface;
Sensitive is not a functional interface. You should be able to make such assignment, as a marker interface does not
contain any methods. In such cases, you need to use a cast with an intersection type that creates a new synthetic type
that is a subtype of all types. The following statement will compile:
Sensitive sen = (Sensitive & Adder) (x, y) -> x + y; // OK
The intersection type Sensitive & Adder is still a functional interface, and therefore, the target type of the
lambda expression is a functional interface with one method from the Adder interface.
 
Search WWH ::




Custom Search