【发布时间】:2020-01-22 18:12:42
【问题描述】:
我目前正在学习 kotlin,并遇到了以下情况。在Ktor 服务器中有一个带有以下签名的方法:
fun Route.webSocket(protocol: String? = null, handler: suspend DefaultWebSocketServerSession.() -> Unit) {
webSocketRaw(protocol) {
proceedWebSocket(handler)
}
}
我应该像这样与它交互的地方:
embeddedServer(Netty, 8080) {
install(Routing) {
webSocket("/ws") {
// Handle websocket connection here
}
}
}
意思是websocket接受labda,它是DefaultWebSocketServerSession的扩展方法,并且有它的上下文。我想将此 lambda 转换为处理程序,以便可以从其他地方传递它,我想它应该看起来像这样:
embeddedServer(Netty, 8080) {
install(Routing) {
webSocket("/ws", myHandler::handle)
}
}
//...
fun suspend handle(context: DefaultWebSocketServerSession): Unit {
// Handle websocket connection here
}
所以,我的问题是如何将suspend DefaultWebSocketServerSession.() -> Unit 转换为(DefaultWebSocketServerSession) -> Unit,或者如何实现一个带有suspend DefaultWebSocketServerSession.() -> Unit 签名的处理程序,以便我可以从外部传递它?
附言
我知道我可以做到这一点
embeddedServer(Netty, 8080) {
install(Routing) {
webSocket("/ws") {
myHandler.handle(this)
}
}
}
但这并不优雅
【问题讨论】:
-
旁注:lamda 不是扩展方法。它被称为带有接收器的函数字面量。
标签: kotlin lambda extension-methods ktor