I have a java constructor which takes a functional interface as a parameter:
public ConsumerService(QueueName queue, Consumer<T> function) {
super(queue);
this.function = function;
}
I'm trying to use this constructor in scala but the compiler complains, saying it cannot resolve the constructor. I've tried the following ways:
val consumer = new ConsumerService[String](QueueName.CONSUME, this.process _)
val consumer = new ConsumerService[String](QueueName.PRODUCE, (s: String) => this.process(s))
I've also tried to cast the function at runtime - but that leaves me with a ClassCastException:
val consumer = new ConsumerService[String](QueueName.CONSUME, (this.process _).asInstanceOf[Consumer[String]])
How can I pass a scala function as a java functional interface parameter?
You need to create a Consumer
:
val consumer = new ConsumerService[String](QueueName.CONSUME,
new Consumer[String]() { override def accept(s: String) = process(s) })
Another way is to use a following library:
https://github.com/scala/scala-java8-compat.
With that in your project once you import:
import scala.compat.java8.FunctionConverters._
you can now write:
asJavaConsumer[String](s => process(s))
which in your code should go like this:
val consumer = new ConsumerService[String](
QueueName.CONSUME,
asJavaConsumer[String](s => process(s))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With