开发者

Is there a bidirectional function in 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?


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜