Java Lambda - Java Intersection Type(Java交集类型)


Java 8 introduced a new type called an intersection type

An intersection type is an intersection of multiple types.

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

An ampersand is used between two types as Type1 & Type2 to represent a new type that is an intersection of Type1, Type2.

Example

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

It creates two interfaces, Calculator is a functional interface and can be used with lambda expression. The other is called NonFunction which is not a functional interface. In order to create a lambda expression and assign to NonFunction we use the & to create a new subtype.

The intersection type NonFunction & Calculator is a functional interface.

public class Main {
  public static void main(String[] argv) {
    //  w w  w. j  a  v a 2s .  c  o  m
    NonFunction nonFunction = (NonFunction & Calculator) (x,y)-> x + y;
  }  
}

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

interface  NonFunction{
}




Example 2

The following code creates an intersection type by intersecting java.io.Serializable marker interface with our own functional interface.

public class Main {
  public static void main(String[] argv) {
    /*from   w ww.j a v  a 2  s  .com*/
    java.io.Serializable ser = (java.io.Serializable & Calculator) (x,y)-> x + y;
  }  
}

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

In this way we make a lambda expression serializable.


http://www.java2s.com/Tutorials/Java/Java_Lambda/0080__Java_Intersection_Type.htm
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值