简体   繁体   English

Kotlin:双冒号(反射)算子结束

[英]Kotlin: double colon (reflection) operator over

So I was working with VertX Web, trying to make it work with Kotlin. 所以我正在使用VertX Web,试图让它与Kotlin一起工作。 There's a router and you have to say something like 有一个路由器,你必须说出类似的东西

val vertx = Vertx.vertx()
val server = vertx.createHttpServer()
val router = Router.router(vertx)
server.requestHandler(router::accept)

But it doesn't work. 但它不起作用。 What am I doing wrong? 我究竟做错了什么? When I use it on Kotlin defined classes, it behaves normally. 当我在Kotlin定义的类上使用它时,它表现正常。 Is it done on purpose? 这是故意的吗?

Whatever, I had to do it manually like this 无论如何,我必须像这样手动完成

server.requestHandler{router.accept(it)}

It is a known bug. 这是一个已知的错误。

See this issue . 看到这个问题

A workaround is to use a Lambda instead. 解决方法是使用Lambda。 eg 例如

class Foo {
  fun doWork(work: () -> Unit) {
    work()
  }
}

class Bar (val text: String) {
  fun printText() {
    println("${text}")
  }
}

val foo: Foo = Foo()
val bar: Bar = Bar("Hello Kotlin!")

foo.doWork(bar::printText) //Fails
foo.doWork({ bar.printText() }) //Is working

Technically it's not a bug. 从技术上讲,这不是一个错误。 I asked early on if they planned to support method references on instances in version 1, and I was told that they most likely wouldn't. 我很早就问过他们是否计划在版本1中的实例上支持方法引用,并且我被告知他们很可能不会。

Method references can only be used from classes and modules, not from instances. 方法引用只能用于类和模块,而不能用于实例。 Coming from Java 8, this seems like a big deal, but considering the potential conciseness of their lambda syntax, it really isn't. 来自Java 8,这似乎是一个大问题,但考虑到他们的lambda语法的潜在简洁性,它实际上不是。

UPDATE: They plan to add this feature in 1.1 更新:他们计划在1.1中添加此功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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