https://kotlinlang.org logo
#ktor
Title
# ktor
j

Jeff Lockhart

11/05/2021, 10:18 PM
Not sure what channel this question best belongs in, but since it's with using Ktor, someone here might have some insight. I have a Ktor
HttpClient
and an
Authenticator
class I'd like to install in the client. In an effort to beautify the code, I'm trying to make the syntax concise. I'd like this to work:
Copy code
class Api(authenticator: Authenticator) {
    private val client = HttpClient {
        Auth {
            authenticator.install() // Unresolved reference: install
        }
    }
    //...
}

class Authenticator(
    private val dependency: Dependency
) {

    fun Auth.install() {
        bearer {
            //...
        }
    }
}
But get "Unresolved reference: install" error. It's not able to call the
install()
function with
Auth
as the receiver. If I change
authenticator.install()
to
with(authenticator) { install() }
or
authenticator.run { install() }
, this works, but obviously not as nice.
Authenticator
has dependencies, which is why the class is necessary and can't be a simple extension function. Is there a better way to format this code to achieve what I'm trying to do as concisely as possible?
r

rnett

11/06/2021, 12:03 AM
No, this has to do with the order of receiver resolution.
class A { fun B.foo() }
expects
A
in the context, and
foo
to be called on
B
. There's no way to change that (see https://youtrack.jetbrains.com/issue/KT-42626), but once context receivers are here you could define it as
context(Auth) fun install()
and get what you're trying to
👍 1
7 Views