How can I write a lambda with a receiver such that...
# stdlib
a
How can I write a lambda with a receiver such that I can write the following style DSL
Copy code
createHttpServer {
            options = myServerOptionsObjectVariableFromAboveSomewhere
            port = 8080
        }
which should run effectively
vertx().createHttpServer(options).listen(port)
?
s
you should be in #vertx for vertx-specific help
the general Kotlin answer to this question is a function that takes
ClassWithOptionsAndPortProperties.() -> Unit
which you can use to apply those settings to your new http server instance and then return it
a
Its not a vertx specific thing - I cannot figure out how to send params from the lambda into the function in this case the options and 8080
Copy code
fun httpServer(f: Vertx.() -> Unit) {
    Vertx.vertx().createHttpServer(options).listen(port)
}
options and port are undefined -- how do i pass them?
s
well, I mean, if options and port are undefined on the
Vertx
object, then you’ll have to write some kind of adapter or builder to translate the parameters you want to accept to the according ones on your end result type
if you only work with properties defined on Vertx, you can do something like
Vertx.vertx().apply(f)
where
f
is your config function
but if you’re looking to build a more DSL-like configuration around the vertx object, you’ll want to maybe write an intermediary
VertexConfig
class you can use
might resemble something like this:
Copy code
class VertxConfig {
  var port: Short = 0
  lateinit var options: VertxOptions
}

fun createHttpServer(block: VertxConfig.() -> Unit): Vertx {
  val config = VertxConfig().apply(block)
  return Vertx.vertx()
      .createHttpServer(config.options)
      .listen(config.port)
}

// usage
createHttpServer {
  port = 8080
  options = serverOptions
}
a
Oh wow perfect!
Thank you man
That’s exactly what i was looking for