模式匹配中的 Scala 擦除

Scala erasure in pattern matching

我必须提取 JSON 响应的信息并评估某些文件是否存在。我正在使用以下方法定义:

override def hasField(field: Field): Boolean = {
  val schema = parse(httpClient.doGet(url + Solr5EndpointUris.schemaOverviewEndpoint)).extract[Map[String, Any]]

  val fieldsNames: List[String] = schema.get("schema") match {
    case schema: Some[Map[String, Any]] => schema.get(if (field.dynamic) "dynamicFields" else "fields") match {
      case fields: List[Map[String, Any]] => fields.map {
        case field: Map[String, Any] => field.get("name") match {
          case name: Some[String] => name.getOrElse("")
        }
      }
      case _ => throw new ApiException("Malformed Response! Missing definition for schema > fields/dynamicFields.")
    }
    case _ => throw new ApiException("Malformed Response! Could not extract schema from JSON.")
  }

  fieldsNames.contains(field.name)
}

该方法通过模式匹配检查 JSON 响应,如果存在具有特定名称的字段,则应该 return 为真。 JSON 响应示例如下:

{
  "responseHeader":{
  "status":0,
  "QTime":2},
  "schema":{
    "name":"example-data-driven-schema",
    "version":1.5,
    "uniqueKey":"id",
    "fieldTypes":[],
    "fields":[{
      "name":"id",
      "type":"string",
      "multiValued":false,
      "indexed":true,
      "required":true,
      "stored":true}],
    "dynamicFields":[],
    "copyFields":[]
  }
}

这个实现确实有效,但我很确定有一个更直接/更简单的实现来实现这个。我也收到很多警告,如下所示:

SchemaManager.scala:38: non-variable type argument Map[String,Any] in type pattern Some[Map[String,Any]] is unchecked since it is eliminated by erasure

任何人都可以提供更好的解决方案,和/或解释我收到的警告吗?

SchemaManager.scala:38: non-variable type argument Map[String,Any] in type pattern Some[Map[String,Any]] is unchecked since it is eliminated by erasure

Scala 编译器将在编译时删除 泛型类型 。所以当你使用 pattern match 时,编译器会擦除你的匹配类型参数。并发出这个警告。它调用 type erasure.

对于您的问题,您可以使用 json4s 作为您的 JSON 摘录:

scala> import org.json4s._
scala> import org.json4s.native.JsonMethods._
scala> val jsonStr = "{\n  \"responseHeader\":{\n  \"status\":0,\n  \"QTime\":2},\n  \"schema\":{\n    \"name\":\"example-data-driven-schema\",\n    \"version\":1.5,\n    \"uniqueKey\":\"id\",\n    \"fieldTypes\":[],\n    \"fields\":[{\n      \"name\":\"id\",\n      \"type\":\"string\",\n      \"multiValued\":false,\n      \"indexed\":true,\n      \"required\":true,\n      \"stored\":true}],\n    \"dynamicFields\":[],\n    \"copyFields\":[]\n  }\n}"
scala> implicit val formats = DefaultFormats
scala> val f = parse(jsonStr)
scala> println((f \ "schema" \ "fields" \ "name").extractOrElse("Null"))
id
scala> println((f \ "schema" \ "fields" \ "unknow").extractOrElse("Null"))
Null

使用extractOrElse设置默认值。