What are the possibilities to design an API that needs overloads depending on a generic type?

…衆ロ難τιáo~ 提交于 2020-01-13 06:05:53

问题


In a given class Example<A> I need the following two functions to be available:

void doSomething(Supplier<A>)

<B> void doSomething(Supplier<B>)

What are the possibilities to achieve this? I know the following approaches:

  1. give the functions different names
  2. use a wrapper-type for the second-definition WrapperType.of(Supplier<B>)
  3. use a function that converts Example<A> to Example<B>

Are there any other approaches?

I dislike 1) as it clutters my API. 2) is really verbose as I have to call said function often and static imports are very unusual outside of testing code. 3) is very explicit about the internal problem which I don't want the user to 'care' about


回答1:


I have found another way by specifying an extension of Function<A,B> as follows:

class SpecificFunction<A,B> extends Function<A,B> {}

Multiple overloads on Function<A,B> and SpecificFunction<A,C> can be defined then which would be impossible without an additional class because of type erasure. This works because the java language specification explicitly enforces that the java compiler has to bind a function call to the most specific function it can find. One part in the defnition of how to find the most specific function is as follows: if two functions m(a) and n(b) exists m(a) is more specific than n(b) if b is not a subtype of a, which holds for our SpecificFunction<A,B>.



来源:https://stackoverflow.com/questions/56098862/what-are-the-possibilities-to-design-an-api-that-needs-overloads-depending-on-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!