问题
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?
回答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.
来源:https://stackoverflow.com/questions/46673632/scala-collections-util-mapstring-anyref-mapstring-string