Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

varargs as input parameter to a function in java 8

Tags:

java

java-8

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> {
//..
} 
like image 459
surya Avatar asked Jan 20 '18 00:01

surya


People also ask

What is Varargs parameter in Java?

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.

At which position Varargs be placed in parameterized method?

Each method can only have one varargs parameter. The varargs argument must be the last parameter.

What symbol is used for a Varargs method parameter?

In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. In order to define vararg, ... (three dots) is used in the formal parameter of a method.

What is the rule for using Varargs?

Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.


1 Answers

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.

like image 186
Ousmane D. Avatar answered Sep 22 '22 05:09

Ousmane D.