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?

2
  • stackoverflow.com/questions/29684894/… but there is no real answer there either... Commented Jul 19, 2016 at 18:22
  • That's a different thing, as there is no Scala involved Commented Jul 19, 2016 at 19:08

2 Answers 2

13

You need to create a Consumer:

val consumer = new ConsumerService[String](QueueName.CONSUME, 
  new Consumer[String]() { override def accept(s: String) = process(s) })
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.