删除 Scala 中的 "eliminated by erasure" 警告

Removing "eliminated by erasure" warning in Scala

我有一个简单的 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(")","]")

但不是 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("[", ",", "]")

您可以执行以下操作,

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")
  }