簡體   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