2016-04-06 166 views
1

我有一個簡單的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]])到刪除的警告,但它不工作。

如何刪除警告?

+1

請看'mkString',好像你的功能可以簡化很多。 'map.toList.map {case(k,v)=> s「」「」$ k「:$ {interpret(v)}」「」} .mkString(「{\ n」,「,\ n」,, 「\ n} \ n」)' –

+0

@Łukasz:太棒了。謝謝! – prosseek

回答

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

你可以做到以下幾點,

case value: String => ??? 
case value: Double => ??? 
case value: Int => ??? 
case value: Seq[Int] @unchecked => ??? 

或@Thilo提到

case value: Seq[_] => 
1

這是更好的代碼,不會產生任何警告信息(來自Thilo 01的提示Ł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") 
    }