Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
Initialize variables with ".()" expression in Kotlin

I'm using Ktor to make websocket requests.
The method "websocket(...)" I use takes two lambda expressions.

enter image description here

So as I only can call one with curly brackets I have to give the other one via a variable. So I tried this:

val request: HttpRequestBuilder.() -> Unit
val socket = ktorHttpClient.webSocket(request = request) {

}

The data types fit now but of course it still says "Variable 'request' must be initialized", so I tried to initialize it:

val request: HttpRequestBuilder.() -> Unit = HttpRequestBuilder.()

Now the error is gone but inside the last brackets it says "Expecting an expression", what am I missing here?

PS: Maybe there's even somebody who can explain in detail how initialization works when using ".()".

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

As you said yourself, you need to pass two lambdas. You can do it either directly:

ktorHttpClient.webSocket({ /* request lambda */ }) {
    /* block lambda */
}

Or split it as you did:

val request: HttpRequestBuilder.() -> Unit = { /* request lambda */ } 
val socket = ktorHttpClient.webSocket(request) {
    /* block lambda */
}

More info on how to initialize lambdas / function types can be found here: https://kotlinlang.org/docs/lambdas.html#instantiating-a-function-type

over 4 years ago · Santiago Trujillo Relatório

0

Just use named parameters with lambdas:

ktorHttpClient.webSocket(request = {}, block = {})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda