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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Does not work either, doStuff requires a Function.
@user3002473 Please explain what errors you are getting. Please give the signature of doStuff.
When I leave is as (x) -> (x + 1), it gives me the error bad operand types for binary operator '+'. If I put (Integer x) -> (x + 1), it says no suitable method found for doStuff((int x)->(x + 1)).
The signature of doStuff is doStuff(Function function).
@user3002473 It's raw. Parameterize it as Function<Integer, Integer> or do what I added in my most recent edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.