8

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?

cscan
  • 3,684
  • 9
  • 45
  • 83
  • http://stackoverflow.com/questions/29684894/is-there-a-standard-way-to-convert-a-java-util-function-consumert-into-a-java but there is no real answer there either... – Alec Jul 19 '16 at 18:22
  • That's a different thing, as there is no Scala involved – Det Jul 19 '16 at 19:08

2 Answers2

13

You need to create a Consumer:

val consumer = new ConsumerService[String](QueueName.CONSUME, 
  new Consumer[String]() { override def accept(s: String) = process(s) })
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
5

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

Michal Przysucha
  • 1,021
  • 11
  • 13