Scala collections: util.Map[String, AnyRef] - Map[String, String]

爱⌒轻易说出口 提交于 2019-12-13 02:58:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!