Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a bidirectional function in Guava?

Tags:

java

guava

So, I need function with API like

interface BiFunction<A, B> {
    B aToB(A input);
    A bToA(B input);
}

Does Guava provided smt like this. If no, what names you would suggest for aToB/bToA methods?

like image 620
Stan Kurilin Avatar asked Mar 25 '11 17:03

Stan Kurilin


3 Answers

No, there isn't anything like this in Guava currently. Something like it may be coming (see this issue, as well as this issue for some related discussion).

For names, I don't know what would be best but I'd prefer something like apply and applyInverse over aToB and bToA.

like image 154
ColinD Avatar answered Oct 05 '22 22:10

ColinD


As of late 2014, Guava 19.0 has it:

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/base/Converter.html

B b = Converter.convert(a);
A a = Converter.reverse().convert(b);

You need to implement the methods:

protected abstract A    doBackward(B b)
protected abstract B    doForward(A a)
like image 45
Sridhar Sarnobat Avatar answered Oct 06 '22 00:10

Sridhar Sarnobat


As for suggested names, it depends on how generic you want to go. Some existing examples are:

interface Codec <I, O> {
    public O encode(I in);
    public I decode(O out);
}

interface Format <R, F> {
    public F format(R raw);
    public R parse(F formatted);
}

If you want it to be super generic, I would just use aToB and bToA as you suggested. Don't make them overloads since you're using Generics, and don't use toA since you're not converting the function itself, you're converting an argument.

like image 29
Mark Peters Avatar answered Oct 06 '22 00:10

Mark Peters