我有一个简单的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]])
删除警告,但它不起作用。
如何删除警告?
如果你真的不关心组件类型(似乎你不关心,因为你所做的只是字符串):
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(")","]")
但考虑Seq#mkString
,而不是toString
然后扰乱字符串
value.mkString("[", ",", "]")
最后,模式isInstanceOf
/asInstanceOf
可以由匹配(在所有情况下)代替
case value: Int => value // it's an Int already now, no cast needed
case value: Seq[_] => value.mkString("[", ",", "]")
您可以执行以下操作,
case value: String => ???
case value: Double => ???
case value: Int => ???
case value: Seq[Int] @unchecked => ???
或者正如@Thilo提到的
case value: Seq[_] =>
这是一个更好的代码,它不会生成警告消息(带有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")
}