【问题标题】:Function "getClient" is never used even when called in MainActivity Kotlin即使在 MainActivity Kotlin 中调用函数“getClient”也不会使用
【发布时间】:2021-04-19 15:27:52
【问题描述】:

在我的 MainActivity 中调用我的 ApiClient 中的函数时,我无法让我的代码作为函数运行,但 intelliJ 说该函数从未使用过。我对 Kotlin 还很陌生,所以这可能是我的语法,但我不完全确定。

这是我的 ApiClient 代码

class ApiClient {
    val ITUNES_BASE_URL = "https://itunes.apple.com/"
    private var retrofit: Retrofit? = null

    fun getClient(): Retrofit? {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(ITUNES_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                //                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //                    .client(client)
                .build()
        }
        return retrofit
    }
}

这是我调用 getClient 的 MainActivity 的 sn-p

  fun displayItunesList() {
        val apiService: ApiInterface = ApiClient.getClient().create(ApiInterface::class)

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    您还有其他 ApiClient 类吗? 应该使用 ApiClient().getClient() 而不是 ApiClient.getClient()。 尝试为您的 Api 客户端添加测试乐趣:

    class ApiClient {
    val ITUNES_BASE_URL = "https://itunes.apple.com/"
    private var retrofit: Retrofit? = null
    
    fun getClient(): Retrofit? {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(ITUNES_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                //                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //                    .client(client)
                .build()
        }
        return retrofit
    }
    
    fun test() {
         ApiClient().getClient()
    }}
    

    【讨论】:

      【解决方案2】:

      试试这个,

      object class ApiClient {
          val ITUNES_BASE_URL = "https://itunes.apple.com/"
          private var retrofit: Retrofit? = null
      
          fun getClient(): Retrofit? {
              if (retrofit == null) {
                  retrofit = Retrofit.Builder()
                          .baseUrl(ITUNES_BASE_URL)
                          .addConverterFactory(GsonConverterFactory.create())
                          //                    
                          .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                          //                    .client(client)
                          .build()
              }
              return retrofit
          }
      }
      

       fun displayItunesList() {
          val apiService: ApiInterface = ApiClient.getClient().create(ApiInterface::class)
      

      【讨论】:

      • 是的,我发现我必须将类更改为对象
      猜你喜欢
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多