In one of the classes, the method of another class RequestInterface is called.

val requestInterface = RequestInterface.getRetrofitBuild(ExampleApi::class.java) 

Where is the getRetrofitBuild method, which returns the required object.

 fun getRetrofitBuild(exampleApi : ExampleApi): ExampleApi { return Retrofit.Builder() .baseUrl(baseDomain) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(exampleApi::class) } 

How can you make it so that not only ExampleApi but also other objects, for example, SimpleApi , can be redone in this method?

 interface ExampleApi { @GET("getItems?") fun getAllItems(@Query("type") type: String): Observable<List<Items>> } interface SimpleApi { @GET("getItems?") fun getAllItems(@Query("lang") language: String): Observable<List<Items>> } 
  • Show these *Api classes somewhere. - Eugene Krivenja
  • Made the edit by adding classes - Dmitriy Gilding
  • Alternatively, you can use this option: inline fun <reified T : Any> getRetrofitBuild(baseDomain: String = Constants.BASE_DOMAIN) : T { return Retrofit.Builder() .baseUrl(baseDomain) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(T::class.java) } Only in this option you cannot use private variables, only public ones - Dmitriy Zolota

1 answer 1

Generics will help you. Quick sketch:

 fun <T> getRetrofitService(clazz: Class<T>): T { return Retrofit.Builder() .baseUrl(baseDomain) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(clazz) } 

The method returns the retorphit service, not the builder. Therefore, I renamed it.