varargs as input parameter to a function in java 8

surya :

In Java 8, how is a Function is defined to fit varargs.

we have a function like this:

private String doSomethingWithArray(String... a){
   //// do something
   return "";
}

And for some reason I need to call it using Java 8 function (because 'andThen' can be used along with other functions.)

And thus I wanted to define it something as given below.

Function<String... , String> doWork = a-> doSomethingWithArray(a)  ;

That gives me compilation error.Following works, but input is now has to be an array and can not be a single string.

Function<String[] , String> doWork = a-> doSomethingWithArray(a)  ;

Here I mentioned String, but it can be an array of any Object.

Is there a way to use varargs(...)instead of array([]) as input parameter?

Or if I create a new interface similar to Function, is it possible to create something like below?

@FunctionalInterface
interface MyFunction<T... , R> {
//..
} 
Ousmane D. :

You cannot use the varargs syntax in this case as it's not a method parameter.

Depending on what you're using the Function type for, you may not even need it at all and you can just work with your methods as they are without having to reference them through functional interfaces.

As an alternative you can define your own functional interface like this:

@FunctionalInterface
public interface MyFunctionalInterface<T, R> {
    R apply(T... args);
}

then your declaration becomes:

MyFunctionalInterface<String, String> doWork = a -> doSomethingWithArray(a);

and calling doWork can now be:

String one = doWork.apply("one");
String two = doWork.apply("one","two");
String three = doWork.apply("one","two","three");
...
...

note - the functional interface name is just a placeholder and can be improved to be consistent with the Java naming convention for functional interfaces e.g. VarArgFunction or something of that ilk.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471935&siteId=1