简体   繁体   English

Scala Map[String, Int] class 施法灾难

[英]Scala Map[String, Int] class cast disaster

Asserting one Map[String, Int] to another in a unit test I get:在单元测试中将一个Map[String, Int]断言到另一个我得到:

Map(bar -> 114, foo -> 5) did not equal Map("foo" -> 5, "bar" -> 114)

Note the keys are not quoted on the left, but are quoted on the right.请注意,键没有在左侧引用,而是在右侧引用。

The left has round tripped through Kafka with Avro serialization as part of a GenericRecord.左边通过 Avro 序列化作为 GenericRecord 的一部分在 Kafka 中往返。 The right is the test fixture which I constructed like this:右边是我这样构建的测试夹具:

program_int_args = Map[String, Int]("foo" -> 5, "bar" -> 114)

Once I get it back from Kafka, I decode the Avro message like this:一旦我从 Kafka 取回它,我就会像这样解码 Avro 消息:

 val program_int_args_ =
        record.get("program_int_args")
          .asInstanceOf[java.util.Map[String, Integer]]
          .asScala
          .toMap[String, Integer]
          .mapValues(Integer2int(_))

Questions:问题:

  1. Why the absence of quotes after coming from the GenericRecord?为什么来自 GenericRecord 后没有引号?
  2. Why the presence of quotes from the constructed map?为什么存在来自构造的 map 的引号?
  3. How can I make these equal?我怎样才能使这些相等?

Per Thomas Klager's comment, I check the classes of the keys, and indeed they are different:根据 Thomas Klager 的评论,我检查了键的类别,确实它们是不同的:

class org.apache.avro.util.Utf8 did not equal class java.lang.String

So updating the question:所以更新问题:

How can the Utf8 type be a key in a Map[String, Int] yet not be equal to the same data as a String ? Utf8类型如何成为Map[String, Int]中的键但不等于与String相同的数据?

I think because of type erasure both conversions我认为由于类型擦除,两种转换

.asInstanceOf[java.util.Map[String, Integer]]

.toMap[String, Integer]

don't really check the type of the keys and values within the map.不要真正检查 map 中的键和值的类型。

You might try你可以试试

val program_int_args_ =
        record.get("program_int_args")
          .asInstanceOf[java.util.Map[Object, Integer]]
          .asScala
          .toMap[Object, Integer]
          .map { case (k, v) => (k.toString, Integer2int(v))}

instead, which converts the keys to String.相反,它将键转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM