我有一个简单的Scala函数,可以从Map[String, Any]
生成一个Json文件。
def mapToString(map:Map[String, Any]) : String = {
def interpret(value:Any) = {
value match {
case value if (value.isInstanceOf[String]) => "\"" + value.asInstanceOf[String] + "\""
case value if (value.isInstanceOf[Double]) => value.asInstanceOf[Double]
case value if (value.isInstanceOf[Int]) => value.asInstanceOf[Int]
case value if (value.isInstanceOf[Seq[Int]]) => value.asInstanceOf[Seq[Int]].toString.replace("List(", "[").replace(")","]")
case _ => throw new RuntimeException(s"Not supported type ${value}")
}
}
val string:StringBuilder = new StringBuilder("{\n")
map.toList.zipWithIndex foreach {
case ((key, value), index) => {
string.append(s""" "${key}": ${interpret(value)}""")
if (index != map.size - 1) string.append(",\n") else string.append("\n")
}
}
string.append("}\n")
string.toString
}
此代码工作正常,但它会在编译中发出警告消息。
Warning:(202, 53) non-variable type argument Int in type Seq[Int] (the underlying of Seq[Int])
is unchecked since it is eliminated by erasure
case value if (value.isInstanceOf[Seq[Int]]) =>
value.asInstanceOf[Seq[Int]].toString.replace("List(", "[").replace(")","]")
^
行case value if (value.isInstanceOf[Seq[Int]])
会导致警告,我尝试case value @unchecked if (value.isInstanceOf[Seq[Int]])
删除警告,但它不起作用。
如何删除警告?
答案 0 :(得分:2)
如果你真的不关心组件类型(似乎你没有,因为你所做的只是将其字符串化):
case value if (value.isInstanceOf[Seq[_]]) =>
value.asInstanceOf[Seq[_]].toString.replace("List(", "[").replace(")","]")
想想看,你应该可以在任何事情上致电toString
:
case value if (value.isInstanceOf[Seq[_]]) =>
value.toString.replace("List(", "[").replace(")","]")
但不是toString
,而是在弄乱字符串时考虑Seq#mkString
value.mkString("[", ",", "]")
最后,该模式isInstanceOf
/ asInstanceOf
可以替换为匹配(在所有情况下)
case value: Int => value // it's an Int already now, no cast needed
case value: Seq[_] => value.mkString("[", ",", "]")
答案 1 :(得分:1)
您可以执行以下操作,
case value: String => ???
case value: Double => ???
case value: Int => ???
case value: Seq[Int] @unchecked => ???
或@Thilo提到
case value: Seq[_] =>
答案 2 :(得分:1)
这是更好的代码,不会产生任何警告信息(来自Thilo&Łukasz的提示)。
def mapToString(map:Map[String, Any]) : String = {
def interpret(value:Any) = {
value match {
case value:String => "\"" + value + "\""
case value:Double => value
case value:Int => value
case value:Seq[_] => value.mkString("[",",","]")
case _ => throw new RuntimeException(s"Not supported type ${value}")
}
}
map.toList.map { case (k, v) => s""" "$k": ${interpret(v)}""" }.mkString("{\n", ",\n", "\n}\n")
}