Issue
In Java, is it possible to have a lambda accept multiple different types?
I.e: Single variable works:
Function <Integer, Integer> adder = i -> i + 1;
System.out.println (adder.apply (10));
Function <Integer [], Integer> multiAdder = ints -> {
int sum = 0;
for (Integer i : ints) {
sum += i;
}
return sum;
};
//....
System.out.println ((multiAdder.apply (new Integer [] { 1, 2, 3, 4 })));
But I want something that can accept many different types of arguments, e.g:
Function <String, Integer, Double, Person, String> myLambda = a , b, c, d-> {
[DO STUFF]
return "done stuff"
};
The main use is to have small inline functions inside functions for convenience.
I've looked around google and inspected Java's Function Package, but could not find. Is this possible?
Solution
It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)
@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
public Six apply(One one, Two two, Three three, Four four, Five five);
}
public static void main(String[] args) throws Exception {
Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}
I've called it Function6
here. The name is at your discretion, just try not to clash with existing names in the Java libraries.
There's also no way to define a variable number of type parameters, if that's what you were asking about.
Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.
Answered By - Sotirios Delimanolis
Answer Checked By - Senaida (JavaFixing Volunteer)