1
votes

I am trying to expose Java method via Scala (from Kafka: https://kafka.apache.org/10/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html).
This is original Java method:

public void commitAsync(OffsetCommitCallback callback)

How to pass callback to a method in Scala? I have something like:

 def commitAsync() = {
    consumer.commitAsync(OffsetCommitCallback callback)
  }

Thanks.
Bonus points - how would look like a test for it e.g. using MockitoSugar?

1

1 Answers

5
votes

You can handle the callback like this:

def commitAsync() = {
   consumer.commitAsync(new OffsetCommitCallback() {
      def onComplete(m: java.util.Map[TopicPartition, OffsetAndMetadata], e: Exception) {
        //...
      }
   })
}

OffsetCommitCallback is an interface, ("similar" as trait in Scala), so you can init an instance anonymously.

Here's is a quick apparition within Spark project.