繁体   English   中英

Authenticator,不正确将Java翻译成Kotlin

[英]Authenticator, incorrect translate Java to 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看起来应该是不同的。

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

不,这本身就是正确的翻译,您可以在SAM转换文档中看到示例。 从错误来看,你可能在范围内还有一些名为Authenticator东西,所以你应该更明确地使用一个匿名对象,就像在Randy Hall的回答中一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM