有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在需要java处理程序的地方传入scala函数

我有scala代码,可以在vertx上处理HttpServerRequest。 其中一个成员(endHandler)需要一个处理程序,其中

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

从scala传入的语法是什么。谢谢


共 (1) 个答案

  1. # 1 楼答案

    不能像在java中传递lambda那样传递scala函数,至少现在还不能。您需要创建一个匿名类,如下所示:

    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)