Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass scala function as java functional interface argument

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?

like image 764
cscan Avatar asked Jul 19 '16 18:07

cscan


2 Answers

You need to create a Consumer:

val consumer = new ConsumerService[String](QueueName.CONSUME, 
  new Consumer[String]() { override def accept(s: String) = process(s) })
like image 149
Jean Logeart Avatar answered Nov 14 '22 05:11

Jean Logeart


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)) )

like image 36
Michal Przysucha Avatar answered Nov 14 '22 06:11

Michal Przysucha