以下显然有效,但我不喜欢在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)));
Run Code Online (Sandbox Code Playgroud)
我想写一些类似的东西:
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));
Run Code Online (Sandbox Code Playgroud)
ty是最有用的帮助.
编辑:问题解决了,开始使用:
public interface T2Function<T> {
T apply(T Val_1, T Val_2);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个函数,因此我可以将函数作为参数传递,例如
public class HashFunction {
private Function f;
public HashFunction(Function f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以写代码
new HashFunction(function(String s){ return s.charAt(0)+0; });
Run Code Online (Sandbox Code Playgroud)
就像在 javascript 中一样。我怎样才能做到这一点?