I'm trying to convert a lot of code Java into Kotlin.
I found on stack how to set authentication with 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();
}
});
It's look simple, but AndroidStudio translate this wrong, something like:
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()
})
and I get error "too many arguments for public open fun Authenticator()"
What is wrong here ? How to fix it ? In my opinion, this should look different in Kotlin.
Your Kotlin code should be like this:
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()
}
})
No, by itself this is a correct translation, you can see examples in SAM Conversions documentation. Judging from the error, you may have something else in scope also called Authenticator
, so you should be more explicit and use an anonymous object as in Randy Hall's answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.