0

This is the interface I'm using:

interface Command {
    void run(int a, int b, int c);
    void run(int a, int b, int c, int d, int e);
}

void add(Command c){

}

this is execution: (using the first run method)

    add((a, b, c) -> System.out.println(""));

The error i get on the execution is:

    The target type of this expression must be a functional interface

And this only goes away when i comment out the second run method.

I want to be able to execute the same interface using both run methods, and not have to create a new interface just to execute with method 2.

How?

1
  • 2
    Say I'm implementing your add method. You call it with add((a, b, c) -> System.out.println(""));. What do you expect to happen if, in the implementation of add, I call c.add(1,2,3,4,5);? Why do you expect that? Commented Nov 12, 2016 at 2:21

1 Answer 1

1

A functional interface by design is allowed to have just one method so what you are trying to do can't be done directly, it's clear why: allowing to implement a functional interface with a lambda must create an object which is valid for its declaration, if it has two methods you cant implement them both with a single lambda.

A workaround could be to use variadic arguments, eg:

@FunctionalInterface
interface Command {
 void run(int... args); 
}

add(args -> { int z = args[0] + args[1] + args[2]; });
Sign up to request clarification or add additional context in comments.

1 Comment

I guess that method works fine, but with that i would have to make an argument an instance of something to call a method: ((Automobile)args[0]).getInCar() is there a way this can be done better?

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.