0

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user3002473
  • 4,835
  • 8
  • 35
  • 61

1 Answers1

4

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

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724