cscan cscan - 4 months ago 17
Java Question

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?

Answer

You need to create a Consumer:

val consumer = new ConsumerService[String](QueueName.CONSUME, 
  new Consumer[String]() { override def accept(s: String) = process(s) })