1

我有一个简单的 Scala 函数,可以从Map[String, Any].

  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]])删除警告,但它不起作用。

如何删除警告?

4

3 回答 3

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("[", ",", "]")
于 2016-04-06T03:48:24.157 回答
1

您可以执行以下操作,

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

或如@Thilo 提到的

case value: Seq[_] => 
于 2016-04-06T03:54:21.770 回答
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")
  }
于 2016-04-06T14:01:02.893 回答