Authenticator,不正确将Java翻译成Kotlin

时间:2018-06-06 21:01:40

标签: java android android-studio kotlin

我正在尝试将大量代码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()
        })

我得到错误“公开开放的有趣的Authenticator()”

的参数太多了

这里有什么问题?怎么解决?在我看来,这在Kotlin看起来应该有所不同。

2 个答案:

答案 0 :(得分:2)

你的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()
  }
})

答案 1 :(得分:1)

不,这本身就是正确的翻译,您可以在SAM Conversions文档中看到示例。从错误来看,你可能在范围内还有一些名为Authenticator的东西,所以你应该更明确地使用anonymous object,就像兰迪霍尔的回答一样。