私はMap[String, Any]
からJsonファイルを生成する単純なScala関数を持っています。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 @unchecked if (value.isInstanceOf[Seq[Int]])
を試してみましたが、それは動作しませんcase value if (value.isInstanceOf[Seq[Int]])
ライン。
警告を削除するにはどうすればよいですか?
'mkString'を見てみてください。あなたの機能が多く簡略化できるようです。 $ {interpret(v)} "" ".mkString(" {\ n "、"、\ n "、" \ n "、" "\ n} \ n") ' –
@Łukasz:それは素晴らしいです。ありがとう! – prosseek