小编Lui*_*eda的帖子

在 kotlin android 中使用 Companion 对象是一个好习惯吗?

我曾经使用Java在android中编程,但是几周前我开始学习kotlin,当我使用Java时我尝试使用面向对象的方法并使用较少可能的静态对象或实例,所以当我在互联网上看到一些材料时关于在 kotlin 中消费 Web 服务的一些实现,我看到如下内容:

/*call of method from activity*/
val message = WebServiceTask.getWebservice(getString(R.string.url_service))

/*Class to do the call to webservice*/
class WebServiceTask {
    companion object {
        fun getWebService(url: String): WebServiceResponse {
            val call =
                RetrofitInstance.getRetrofit(url).create(ApiService::class.java).getList()
                    .execute()
            val webServiceResponse = call.body() as WebServiceResponse
            return user
        }
    }
}
/*Class to get Retrofit instance*/
class RetrofitInstance {
    companion object{
        fun getRetrofit(url: String): Retrofit {
            return Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }

    }
} 
Run Code Online (Sandbox Code Playgroud)

就像你看到的我在两个类中使用伴生对象,根据我读过的伴生对象相当于 java 中的静态实例,所以我的问题是:这段代码是否遵循面向对象编程?,推荐这种方法吗?,如果答案是不,这是面向对象中这段代码的最佳实现

android kotlin

4
推荐指数
1
解决办法
3670
查看次数

标签 统计

android ×1

kotlin ×1