传入需要 java 处理程序的 Scala 函数

Passing in a scala function where a java handler is expected

我有设置为处理 vertx 上的 HttpServerRequest 的 Scala 代码。 其中一个成员 (endHandler) 需要一个 Handler where

public interface Handler<E> {
   void handle(E event);
}

从 scala 传递进来的语法是什么。谢谢

您不能像在 java 中传递 lambda 那样只传递 scala 函数,至少现在不能。您需要像这样创建一个匿名 class:

new Handler[Int] {
  override def handle(event: Int): Unit = {
    // some code
  }
}

为方便起见,您可以创建辅助方法

implicit def functionToHandler[A](f: A => Unit): Handler[A] = new Handler[A] {
  override def handle(event: A): Unit = {
    f(event)
  }
}

如果你使用这个方法implicit那么你就可以简单地传递 scala 函数

所以总结

def client(handler: Handler[Int]) = ??? // the method from java
val fun: Int => Unit = num => () // function you want to use

你可以这样做:

client(new Handler[Int] {
  override def handle(event: Int): Unit = fun(event)
})

使用辅助方法:

client(functionToHandler(fun))

隐式转换:

client(fun)