Bill Michaelson
Bill Michaelson

Reputation: 376

How to use Scala match/case against Collection type without triggering compiler warning

My code is analyzing a structure returned via JSON. I take the parsed JSON and use a match/case to determine if I have a Map[String,Any] before further processing. It works fine, but the compiler warns me about type erasure, specifically, as I understand it, because the type String is unavailable at run time. This no problem for me in terms of functionality because it is sufficient for me to simply know that we have Map. But I appreciate the warning and would prefer to code it in a way that makes explicit that such runtime checking is not occurring and to eliminate the warning. I tried simply coding Map instead of Map[...] but that does not compile. I also tried Map[Any,Any] but that still generates a warning.

I am seeking recommendations.

Also, I am puzzled about why a later case using List[Any] does not cause a similar warning to be issued.

Here is the code fragment:

  // Parse JSON result - returns List[Any] or Map[String,Any], depending...
  val jo = scala.util.parsing.json.JSON.parseFull(json)
  //println("\nParsed JSON structure: "+jo)
  jo match {
    case Some(v)  => {
      val pjo = jo.get
      println()
      pjo match {
        case p: Map[String,Any] => {
          //println("Is a Map")
          val eList = p.get("error")
          if (eList.size > 0) {
            println("Errors:")
            for (e <- eList) println(e)
            println
          }
        }
        case p: List[Any] => println("Is a List")
        case p => println("Is a "+p.getClass.getName)
      }
    }
    case None => println("JSON parsing returned None")
  }

warning:

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

Upvotes: 1

Views: 129

Answers (1)

Daenyth
Daenyth

Reputation: 37461

You need to use an underscore:

case p: Map[_, _] => ...
case p: List[_] => ...

Upvotes: 1

Related Questions