Arhowk
Arhowk

Reputation: 931

Lambda functions with an indefinite number of arguments

I'm trying to pull off something like whats given in the code. I want a lambda expression thats able to accept any function

interface ExecuteAnyCode{
    void execute(Object... args);
}

void entry(){
    ExecuteAnyCode a = Math::sin;
    ExecuteAnyCode b = System.out::println;

    a.execute(5);
    b.execute("Hello World")
}

but it gives me an errror regarding the arguments in the functions passed to the functional interface. Is there any way to do this?

Upvotes: 2

Views: 185

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

Your functional interface defines a method that accepts a Object.... Whatever method reference you use as an assignment to a variable of that functional interface type must have a matching signature. Math::sin does not.

The ExecuteAnyCode#execute method allows you to invoke it as

ref.execute(1, 2, "3", 4, new Something());

What would that do if you had

ExecuteAnyCode ref = Math::sin;
ref.execute(1, 2, "3", 4, new Something());

What would be passed to Math.sin?

The language does not allow what you are trying to do. Lambdas and method references require that this information is known at compile time.

Upvotes: 7

Related Questions