Home > Software engineering >  Initialize variables with ".()" expression in Kotlin
Initialize variables with ".()" expression in Kotlin

Time:02-28

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 ".()".

CodePudding user response:

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

  • Related