0

I'm new to writing code in Scala. I'm trying to iterate over a java Map with custom objects as key value pairs. Specifically I'm trying to go over the Map of TopicPartitions and OffSetMetadata Map when committing offsets to Kafka.

Here is the code that i have written

override def onComplete(map: util.Map[TopicPartition, OffsetAndMetadata], e: Exception): Unit = {
  val sb = new StringBuffer()
  map.forEach((partition:TopicPartition ,offsets : OffsetAndMetadata) => {
    sb.append(partition.topic()+","+partition.partition()+","+offsets.offset()+"\n")
  })

However I get a compilation error saying

error: type mismatch; found : (org.apache.kafka.common.TopicPartition, org.apache.kafka.clients.consumer.OffsetAndMetadata) => StringBuffer [ERROR] required: java.util.function.BiConsumer[_ >: org.apache.kafka.common.TopicPartition, _ >: org.apache.kafka.clients.consumer.OffsetAndMetadata] [ERROR] map.forEach((partition:TopicPartition ,offsets : OffsetAndMetadata) => { [ERROR] ^

It indicates the => operator while pointing the error, any help is appreciated.

2
  • 2
    Seems to work here (with maps of other classes). Could you make a complete example which reproduces the error? Commented Jan 23, 2019 at 19:35
  • 2
    Why don't you try converting the map from Java to Scala first? Commented Jan 23, 2019 at 19:36

1 Answer 1

3

The best bet I have is that you use Scala 2.11 that is still not really aware of Java 8 and functional interfaces. That's why the compiler can't automatically convert your Scala lambda to a matching BiConsumer. According to my understanding the simplest workaround is to create a BiConsumer explicitly as in

override def onComplete(map: util.Map[TopicPartition, OffsetAndMetadata], e: Exception): Unit = {
  val sb = new StringBuffer()
  map.forEach(new java.util.function.BiConsumer[TopicPartition, OffSetMetadata]() {
    def accept(partition: TopicPartition, offsets: OffSetMetadata ) = {
      sb.append(partition.topic() + "," + partition.partition() + "," + offsets.offset() + "\n")
    }
  })
}

Well the other work-around is to wrap Java-Map into a Scala-Map first and use Scala interface. And of course you can upgrade to Scala 2.12 where this conversion of lambda to BiConsumer is done by the compiler.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, I am indeed using Scala 2.11 , this worked! Thanks for the help!

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.