I am trying to translate Java Retrofit Api client code to Kotlin. So here is what we have in Java:
Retrofit client which returns retrofit singleton object:
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
And Api client which uses the above retrofit object:
public class ApiUtils {
public static final String BASE_URL = "https://api.stackexchange.com/2.2/";
public static SOService getSOService() {
return RetrofitClient.getClient(BASE_URL).create(SOService.class);
}
}
The problem is that in every example I have seen so far on the internet, uses companion object(every member inside it is static), why then our singleton pattern passes away? Why not to use object instead of companion object and how to do that? See the example with companion object in Kotlin:
interface WikiApiService {
@GET("api.php")
fun hitCountCheck(@Query("action") action: String): Observable<Model.Result>
companion object {
fun create(): WikiApiService {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://en.wikipedia.org/w/")
.build()
return retrofit.create(WikiApiService::class.java)
}
}
Let alone that this is done in the same class, using companion object will result in returning new object of both retrofit and WikiApiService. I cannot be agree with it. Please make any clarifications about these examples. Maybe I don't get anything that's why this seems to me wrong and please forgive that I have put different examples for Java and Kotlin.