我创建了一个简单的Avro(1.7.7)模式,并让Avro生成了Java类,这些Java类被震荡并添加到我的Spark项目中。在生成的Java类中,我有:

public java.util.List<java.util.Map<java.lang.CharSequence,java.lang.CharSequence>> attributes;


作为从架构创建的代码的一部分,如下所示:

{
  "namespace": "com.rbh.avro.metric",
  "type": "record",
  "name": "Metric",
  "fields": [
    { "name": "consumerId", "type": "long" },
    {
      "name": "data",
      "type": {
        "name": "Data",
        "type": "record",
        "fields": [
          { "name": "name", "type": "string" },
          { "name": "attributes",
            "type": {
              "type": "array",
              "items": {
                "type": "map",
                "values": "string"
              }
            }
          }
        ]
      }
    }
  ]
}


因此,由于StringCharSequence,我正在测试的一些代码如下所示:

val data:Data = Data.newBuilder.setName("myData").build
val x = Map("a" -> "1", "b" -> "2", "c" -> "3").asJava
val y = Map("x" -> "42", "y" -> "27", "z" -> "-1").asJava
val z = Map("g" -> "a", "h" -> "*", "i" -> "~").asJava
val xyz = List(x,y,z).asJava
data.setAttributes(xyz)


Eclipse立即抱怨并在编译时抱怨(Scala 2.10.5和SBT 0.13.8),我看到:

[error] /home/bkarels/dev/spark/event-gen/src/main/scala/com/rbh/generator/Generator.scala:60: type mismatch;
[error]  found   : java.util.List[java.util.Map[String,String]]
[error]  required: java.util.List[java.util.Map[CharSequence,CharSequence]]
[error]         data.setAttributes(xyz)
[error]                            ^
[warn] 5 warnings found
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 11 s, completed Jun 26, 2015 8:12:31 AM


我开始困惑了...

因此,我打开了REPL会话,此方法有效:

scala> def foo(cs:CharSequence) = {
     |   println(cs)}
foo: (cs: CharSequence)Unit

scala> def s:String = "bar"
s: String

scala> foo(s)
bar


为了进行某种形式的验证,我还将这段代码放入其中,并按预期进行编译和运行:

val data:Data = Data.newBuilder.setName("myData").build
val cs0:CharSequence = "xxx"
val w = Map(cs0 -> cs0).asJava
val wl = List(w).asJava
data.setAttributes(wl)


就像人们可能期望的那样,这种笨拙的冗长并不是一个有翅膀的“解决方案”。

所以有些事情是不对的,但是我对它可能是什么感到茫然。如果您有想法请告诉我-谢谢。

最佳答案

Map[String, String]不是Map[CharSequence, CharSequence],因为Map[CharSequence, CharSequence]允许添加非String的键/值对。请参阅此SO question,以获得出色的答案。

关于java - 在Avro生成的Java类上的Scala中预期在CharSequence的String上获取类型不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31074813/

10-10 12:31