Vert.x需要Kotlin类型不匹配处理程序<AsyncResult <Unit >> found(Handler <AsyncResult <Unit >>) – > Unit

以下是Java中Kotlin重写的方法:

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

但是,当我打电话如下:

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

我得到错误Type Mismatch required Handler<AsyncResult<Unit>> found (Handler<AsyncResult<Unit>>) -> Unit

我究竟做错了什么?

您的lambda应采用Handler接口的单一方法所采用的参数,即AsyncResult<Unit> 。 你的lambda Handler ,所以它不把Handler作为参数。

我想你还需要在这里明确地调用SAM构造函数,因为你的函数是用Kotlin编写的,看起来像这样:

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

这将创建一个Handler<AsyncResult<Unit>> ,其中lambda表示其单一方法。

最后,你可以省略lambda里面的类型来减少冗余:

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