Reputation: 2311
I have been using the Guava Function interface public interface Function<F, T>
and while its useful for f(F)=T
type computation. I have encountered many cases where I need computation for variable arguments i.e
f(A,B,C...)=X
Now I recently came across the java tuples library http://www.javatuples.org/ which does a neat job upto 10 arguments. However I wanted something more generic. Instead of explicitly declaring getters and setters for the individual classes. My question is, is it possible to declare something like this
public interface Function2<Class<? extends Object>...,T>
which can operate on variable number of type parameters. Although I know having a class and using its corresponding fields is a better option, I just wanted to know this.
As the use case for such functions is asked I am writing about such an use with the Functional Java library(which supports upto 8 arguments) although its a very trivial use case. Eg: Given 2 string return true if they are equal else return false:
F2<String, String, Boolean> stringsEqual = new F2<String, String, Boolean>() {
@Override
public Boolean f(final String a, final String b) {
return a.equals(b);
}
Upvotes: 1
Views: 1043
Reputation: 62864
No, you are not allowed to use varargs in Generics.
However, a possible approach you can follow is to use a list that holds all the function arguments:
public interface Function2<T extends List<?>, U> {
public U apply(T argumentList);
}
Another approach is to define the varargs in the abstract method, but in the context of Generics, they should be of compatible types (because we can't define infinite amount of type arguments that don't have relation). For example:
public interface Function2<T, U> {
public U apply(T ... argumentList);
}
Upvotes: 2