我开始使用Scala,我正在用JavaConversions
替换已弃用的JavaConverters
库。我有以下代码:
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()
}
当我将JavaConversions
的导入替换为JavaConverters
(或者只是完全注释掉导入)时,我得到了编译异常:
Type mismatch expected: util.Map[String, AnyRef], actual Map[String, String]
我错过了什么?
答案 0 :(得分: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.