Lambda expression with variable length parameters

Viewed 32

When i trying write in method variable length parameters(int ...x), i have this problem : "Operator '+' cannot be applied to 'int[]','int'" i want to understand, can i use (int ...x) when i use lambdas, and if can, how?

class calculations {
    public static void main(String[] args) {
        func obj = (x) -> x+1;
        int result = obj.sum(10);
        System.out.println(result);
    }
}
interface func {
    int sum(int ...x);
}

I know that variable length parameters(int ...x) indicates that it will be optional and will represent an array, based on this i can add multiple parametrs, for example func obj = (x,y,w) -> x+y+w; but it's dont work.

1 Answers

In your code, x isn't an int, but an array int[]. Because method sum() expects varags of int (i.e. all the arguments would be wrapped with an auxiliary array).

For that, reason, you're getting a compilation error.

That's how the proper implementation might look like:

func obj = x -> Arrays.stream(x).sum();

Or you can apply some operations, for instance increment each element by 1, like you were trying in your code:

func obj = x -> Arrays.stream(x).map(i -> i + 1).sum();

Sidenote: interface name func isn't aligned with the Language naming conventions. It should start with a capital letter. Also, name func doesn't conveys the purpose of the interface (see Self-documenting code).

Related