java8箭头怎么输入_在Java 8中,带有2个箭头的lambda是什么意思?

问题

我以前读了几篇Java 8教程。

在这里,我看到以下代码:

IntFunction curriedAdd = a -> b -> a + b;

System.out.println(curriedAdd.apply(1).applyAsInt(12));

我明白这个例子总结了2个元素,但我无法理解构造:

a -> b -> a + b;

根据表达式的左侧部分,该行应实现以下功能:

R apply(int value);

在此之前,我只用一个箭头遇到了lambdas。

#1 热门回答(113 赞)

如果你把它表达为非简写lambda语法或pre-lambda Java匿名类语法,那么发生的事情会更清楚......

原来的问题。为什么是两支箭?很简单,定义了两个函数...第一个函数是函数定义函数,第二个函数是函数的结果,它也恰好是函数。每个都需要a->operator来定义它。

##非速记

IntFunction curriedAdd = (a) -> {

return (b) -> {

return a + b;

};

};

在Java 8之前的## Pre-Lambda

IntFunction curriedAdd = new IntFunction() {

@Override

public IntUnaryOperator apply(final int value) {

IntUnaryOperator op = new IntUnaryOperator() {

@Override

public int applyAsInt(int operand) {

return operand + value;

}

};

return op;

}

};

#2 热门回答(45 赞)

AnIntFunction是一个函数int -> R。 AnIntUnaryOperator是一个函数int -> int。

因此,anIntFunction是一个函数,它接受一个intas参数并返回一个带有intas参数并返回aint的函数。

a -> b -> a + b;

^ | |

| ---------

| ^

| |

| The IntUnaryOperator (that takes an int, b) and return an int (the sum of a and b)

|

The parameter you give to the IntFunction

也许更清楚的是你是否使用匿名类来"分解"lambda:

IntFunction add = new IntFunction() {

@Override

public IntUnaryOperator apply(int a) {

return new IntUnaryOperator() {

@Override

public int applyAsInt(int b) {

return a + b;

}

};

}

};

#3 热门回答(27 赞)

添加括号可能会更清楚:

IntFunction curriedAdd = a -> (b -> (a + b));

或者可能中间变量可能有所帮助

IntFunction curriedAdd = a -> {

IntUnaryOperator op = b -> a + b;

return op;

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值