Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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 answers
Answer question

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 Report

0

Just use named parameters with lambdas:

ktorHttpClient.webSocket(request = {}, block = {})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!