简体   繁体   中英

Vert.x Kotlin Type Mismatch required Handler<AsyncResult<Unit>> found (Handler<AsyncResult<Unit>>) -> Unit

The following is a method rewritten in Kotlin from Java:

fun publishMessageSource(
        name: String,
        address: String,
        completionHandler: Handler<AsyncResult<Unit>>
) {
    val record = MessageSource.createRecord(name, address)
    publish(record, completionHandler)
}

However, when I call it as follows:

publishMessageSource("market-data", ADDRESS, { record: Handler<AsyncResult<Unit>> ->
            if (!record.succeeded()) {
                record.cause().printStackTrace()
            }
            println("Market-Data service published : ${record.succeeded()}")
        })

I get the error Type Mismatch required Handler<AsyncResult<Unit>> found (Handler<AsyncResult<Unit>>) -> Unit .

What am I doing wrong?

Your lambda should take the parameter that the single method of the Handler interface takes, which is AsyncResult<Unit> in this case. Your lambda is the Handler , so it doesn't take the Handler as a parameter.

I think you'll also need an explicit call to the SAM constructor here, since your function is written in Kotlin, that would look something like this:

publishMessageSource("market-data", ADDRESS, Handler<AsyncResult<Unit>> { record: AsyncResult<Unit>  ->
    ...
})

This creates a Handler<AsyncResult<Unit>> with a lambda representing its single method.

Finally, you can omit the type inside the lambda to be less redundant:

publishMessageSource("market-data", ADDRESS, Handler<AsyncResult<Unit>> { record ->
    ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM