Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

Just use named parameters with lambdas:

ktorHttpClient.webSocket(request = {}, block = {})
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda