我有一個簡單的Scala函數,可以從Map[String, Any]
生成Json文件。在Scala中刪除「通過刪除消除」警告
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]])
到刪除的警告,但它不工作。
如何刪除警告?
請看'mkString',好像你的功能可以簡化很多。 'map.toList.map {case(k,v)=> s「」「」$ k「:$ {interpret(v)}」「」} .mkString(「{\ n」,「,\ n」,, 「\ n} \ n」)' –
@Łukasz:太棒了。謝謝! – prosseek