I have question about passing method reference as argument in java (util) functions.
I have two functions
Function<Value, Output> f1 = (val) -> {
Output o = new Output();
o.setAAA(val);
return o;
};
Function<Value, Output> f2 = (val) -> {
Output o = new Output();
o.setBBB(val);
return o;
};
I want to merge them into one function which should looked like
BiFunction<MethodRefrence, Value, Output> f3 = (ref, val) -> {
Output o = new Output();
Output."use method based on method reference"(val);
return o;
};
I want to use this function like
f3.apply(Output::AAA, number);
Is it possible ? I can't figure out correct syntax, how to make such a function.
It looks like you want a function like
BiFunction<BiConsumer<Output,Value>, Value, Output> f = (func, val) -> {
Output o = new Output();
func.accept(o, val);
return o;
};
which you can invoke like
f.apply(Output::setAAA, val);
f.apply(Output::setBBB, val);
I'm not quite sure what you mean with "method reference", but I think you want something like this:
BiFunction<Integer, Value, Output> f3 = (ref, val> -> {
switch(ref) {
case 1: return f1.apply(value);
case 2: return f2.apply(value);
default: throw new IllegalArgumentException("invalid index");
}
}
You can replace the Integer with anything you'd like, as long as you also change the switch-statement, maybe use an if/else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.