Reputation: 20038
Following obviously works, but I do not like to wrap items in Tuple,
ImmutableMap<String, Function<Tuple2<Double>, Double>> op = new //
ImmutableMap.Builder<String, Function<Tuple2<Double>, Double>>()
.put("+", new Function<Tuple2<Double>, Double>() {
@Override public Double apply(Tuple2<Double> data) {
return data.Val_1 + data.Val_2;
}
}).build();
System.out.println(op.get("+").apply(new Tuple2<Double>(3d, 4d)));
I want to write something like:
ImmutableMap<String, Function<Double[], Double>> op = new //
ImmutableMap.Builder<String, Function<Double[], Double>>()
.put("+", new Function<Double[], Double>() {
@Override
public Double apply(Double... data) {
return data[0] + data[1];
}
}).build();
System.out.println(op.get("+").apply(3d, 4d));
Help would be most useful, ty.
Edit: Problem solved, started using:
public interface T2Function<T> {
T apply(T Val_1, T Val_2);
}
Upvotes: 9
Views: 9552
Reputation: 581
It looks like you're after an equivalent to c#'s Func: Specialised in your case with the args and return value of the same type.
There's two other questions with good answers about this..
As some other answers hint at, you may be stuck in the middle between two paradigms here (OO and functional), something with which language design is arguably catching up quicker than good practice is. If you want to continue down that murky water, you could try functionaljava.
See Mixing object-oriented and functional programming for more interesting discussion.
Upvotes: 3
Reputation: 110046
I think you'd be better off using an interface of your own, something like this:
public interface Operation {
double apply(double a, double b);
}
Guava's Function
is a single argument function and not really appropriate for anything multi-argument.
Another thing I've experimented with is a ReduceFunction<F, T>
that happens to be usable for such a thing. It's for use with the reduce
or fold
operation and looks something like:
public interface ReduceFunction<F, T> {
T apply(T a, F b); // I can't decide on good names for the parameters =(
}
This lets you do things like
List<Double> doubles = ...
Double sum = reduce(doubles, MathOps.add(), 0.0);
where MathOps.add()
is a ReduceFunction<Double, Double>
that does the obvious thing.
Upvotes: 15