0

I am getting started with Scala and I am replacing the deprecated JavaConversions library with JavaConverters. I have the following code:

import scala.collection.JavaConversions._

new AMQP.BasicProperties.Builder()
  .contentType(message.contentType.map(_.toString).orNull)
  .contentEncoding(message.contentEncoding.orNull)
  .headers(message.headers) //<<<<--------------- I SEE THE ERROR ON THIS LINE (datatype of message.heads is Map[String, String]
  .deliveryMode(toDeliveryMode(message.mode))
  .priority(..)
  .correlationId(..)
  .replyTo(..)
  .expiration(..)
  .messageId(..)
  .timestamp(..)
  .`type`(..)
  .userId(..)
  .appId(..)
  .build()

}

When I replace the import for JavaConversions to JavaConverters (or, just comment out the import altogether), I get the compilation exception:

Type mismatch expected: util.Map[String, AnyRef], actual Map[String, String]

What am I missing?

2
  • 1
    you're missing .asJava obviously util.Map[String, AnyRef] is a Java collection Map[String, String] is a Scala collection Commented Oct 10, 2017 at 18:36
  • @dk14 can you please elaborate? Where do I need to add the .asJava? Commented Oct 10, 2017 at 18:38

1 Answer 1

1

You're missing .asJava obviously - explicit conversion is the whole point of using JavaConverters. util.Map[String, AnyRef] is a Java collection, Map[String, String] is a Scala collection. You need at least

.headers(message.headers.asJava.asInstanceOf[java.util.Map[String, AnyRef]])

or better to do type-cast safely before calling asJava:

val params: Map[String, AnyRef] = message.headers
...
.headers(params.asJava)

P.S. The reason you've got a second error after just doing asJava isn't Scala or JavaConvertors related, it's just that V in java.util.Map[K,V] isn't covariant (it's invariant, unlike in Scala's Map[K, +V]). Actually compiler messages explains it:

Note: String <: AnyRef, but Java-defined trait Map is invariant in type V.

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

2 Comments

now I see: Type mismatch expected: util.Map[String, AnyRef], actual util.Map[String, String]
@Darth.Vader this isn't related to Scala or converters - java's map isn't contra-variant on second argument, so you have to do it java style (typecast). Basically compiler message suggests it: "Note: String <: AnyRef, but Java-defined trait Map is invariant in type V."

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.