【问题标题】:Authenticator, incorrect translate Java to Kotlin身份验证器,不正确地将 Java 转换为 Kotlin
【发布时间】:2018-06-06 21:01:39
【问题描述】:

我正在尝试将大量 Java 代码转换为 Kotlin。

我在堆栈上找到了如何使用 OkHttp 设置身份验证:

 client.authenticator(new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            if (responseCount(response) >= 3) {
                return null; // If we've failed 3 times, give up. - in real life, never give up!!
            }
            String credential = Credentials.basic("name", "password");
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    });

看起来很简单,但AndroidStudio翻译错了,类似于:

   client.authenticator(Authenticator { route, response ->
            if (responseCount(response) >= 3) {
                return@Authenticator null // If we've failed 3 times, give up. - in real life, never give up!!
            }
            val credential = Credentials.basic("name", "password")
            response.request().newBuilder().header("Authorization", credential).build()
        })

我收到错误“public open fun Authenticator() 的参数太多”

这里有什么问题?如何解决?在我看来,这在 Kotlin 中应该会有所不同。

【问题讨论】:

    标签: java android android-studio kotlin


    【解决方案1】:

    你的 Kotlin 代码应该是这样的:

    client.authenticator(object:Authenticator {
      @Throws(IOException::class)
      fun authenticate(route:Route, response:Response):Request {
        if (responseCount(response) >= 3)
        {
          return null // If we've failed 3 times, give up. - in real life, never give up!!
        }
        val credential = Credentials.basic("name", "password")
        return response.request().newBuilder().header("Authorization", 
    credential).build()
      }
    })
    

    【讨论】:

    • @Throws 不是必需的,您应该将override 添加到fun authenticate
    • 我得到了 AndroidStudio 这个对象的下划线:Authenticator with "too many arguments for public open fun authenticationator()"
    • 1. authenticator 还是 Authenticator? 2.尝试去定义,看看AS认为它指的是什么。
    【解决方案2】:

    不,这本身就是一个正确的翻译,您可以在SAM Conversions 文档中查看示例。从错误来看,您可能在范围内还有其他东西,也称为Authenticator,因此您应该更明确地使用anonymous object,如 Randy Hall 的回答。

    【讨论】:

    • 我有类似 Randy asnwer 的匿名类,但仍然有这个错误
    猜你喜欢
    • 2013-05-12
    • 2015-05-03
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多