传入一个需要java处理程序的scala函数

时间:2022-10-04 18:06:32

I have scala code that is setup to handle HttpServerRequest on vertx. One of the members (endHandler) expects a Handler where

我有设置为在vertx上处理H​​ttpServerRequest的scala代码。其中一个成员(endHandler)期望Handler在哪里

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

What would the syntax be to pass in this from scala. thanks

从scala传递的语法是什么?谢谢

1 个解决方案

#1


3  

You cannot just pass scala function as you would pass lambda in java, at least not yet. You need to create an anonymous class like this:

你不能只传递scala函数,就像在java中传递lambda一样,至少现在还没有。你需要创建一个这样的匿名类:

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

for convenience you can create helper method

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

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

If you make this method implicit then you are able to simply pass scala function

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

so to wrap up

所以结束

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

you can do this:

你可以这样做:

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

with helper method:

辅助方法:

client(functionToHandler(fun))

with implicit conversion:

隐式转换:

client(fun)

#1


3  

You cannot just pass scala function as you would pass lambda in java, at least not yet. You need to create an anonymous class like this:

你不能只传递scala函数,就像在java中传递lambda一样,至少现在还没有。你需要创建一个这样的匿名类:

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

for convenience you can create helper method

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

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

If you make this method implicit then you are able to simply pass scala function

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

so to wrap up

所以结束

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

you can do this:

你可以这样做:

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

with helper method:

辅助方法:

client(functionToHandler(fun))

with implicit conversion:

隐式转换:

client(fun)