I'm having trouble with Java 8's syntax for lambda expressions, I can't seem to create one on the fly in one line. The following code works,
Function<Integer, Integer> increment = (x) -> (x + 1);
doStuff(increment);
but the following lines do not
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;}));
and I'm not quite sure what else I can try. I certainly don't want to use
doStuff(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer x){
return x + 1;
}
});
so what else is there? I've looked through a bunch of questions on lambda expression syntax and nothing seems to be working.
Simply
doStuff((x) -> (x + 1));
You had
Function<Integer, Integer> increment = (x) -> (x + 1);
doStuff(increment);
So just replace it with the right hand side of =
(generally).
(x) -> (x + 1)
If doStuff
's single parameter is not of type Function<Integer, Integer>
, you'll need a target functional interface type
doStuff((Function<Integer,Integer>) (x) -> (x + 1));
Your method was using a raw Function
type. Read
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.