2014-12-07 112 views
0

我在使用lambda表达式的Java 8语法时遇到了问题,我似乎无法在一行中创建一个。下面的代码工作,Java 8:将java.util.function.Function作为Lambda表达式实现的语法

Function<Integer, Integer> increment = (x) -> (x + 1); 
doStuff(increment); 

但以下行没有

doStuff((x) -> (x + 1)); 
doStuff(Function (x) -> (x + 1)); 
doStuff(new Function (x) -> (x + 1)); 
doStuff(Function<Integer, Integer> (x) -> (x + 1)); 
doStuff(new Function(Integer, Integer> (x) -> (x + 1)); 
doStuff(new Function<Integer, Integer>(x -> {x + 1;})); 

,我不太清楚还有什么我可以试试。我当然不想使用

doStuff(new Function<Integer, Integer>() { 
    @Override 
    public Integer apply(Integer x){ 
     return x + 1; 
    } 
}); 

那么还有什么呢?我查看了一堆关于lambda表达式语法的问题,但似乎没有任何工作。

回答

4

只需

doStuff((x) -> (x + 1)); 

你有

Function<Integer, Integer> increment = (x) -> (x + 1); 
doStuff(increment); 

所以只要用=(一般)右侧更换。

(x) -> (x + 1) 

如果doStuff的一个参数是Function<Integer, Integer>型的没有,你需要一个目标功能接口类型

doStuff((Function<Integer,Integer>) (x) -> (x + 1)); 

你的方法是使用原始Function类型。阅读

+0

也不管用,'doStuff'需要'Function'。 – user3002473 2014-12-07 00:25:57

+1

@ user3002473请解释你所得到的错误。请给出'doStuff'的签名。 – 2014-12-07 00:27:10

+0

当我离开时是'(x) - >(x + 1)',它给了我错误'二元运算符的错误操作数类型'+''。如果我把'(Integer x) - >(x + 1)',它表示没有为doStuff((int x) - >(x + 1))找到合适的方法。 – user3002473 2014-12-07 00:28:54