generics - Scala type erasure in pattern matching Map[String, Int] -


in scala 2.10, compiler warns given code:

  private def getstrfromopt[t](opt: option[t]): string = opt match {     case some(s: string) => s     case some(i: int) => i.tostring()     case some(l: long) => l.tostring()     case some(m: map[string, int]) => m map ({ case (k, v) =>       "(" + k + ", " + v + ")" }) mkstring ("(", ", ", ")")     case _ => ""   } 

with message non-variable type argument string in type pattern map[string,int] unchecked since eliminated erasure: case some(m: map[string, int]) ....

how can rid of warning? if have map[string, myobj] want include case in matching - how can distinguish 2 cases parameterised maps?

you can use scala annotation @unchecked suppress warning, second question, suggest use scala reflection -- typetag. using scala 2.11.4, here sample code, fyi.

import scala.reflect.runtime.{ universe => ru } import scala.reflect.runtime.universe.{ typetag, typetag }  object maptype extends app {   def gettypetag[t: typetag](t: t) = typetag[t].tpe   def gettypetag[t: typetag] = ru.typeof[t]    // context bound t: ru.typetag cause typeof    // requires implicit parameter   def getstrfromopt[t: typetag](opt: option[t]): string = {     opt match {        case some(s: string) => s        case some(i: int) => i.tostring()        case some(l: long) => l.tostring()        case some(m: map[string, int] @ unchecked)           if gettypetag[t] =:= gettypetag[map[string, int]] => "int map"        case some(m: map[string, string] @ unchecked)           if gettypetag[t] =:= gettypetag[map[string, string]] => "string map"        case _ => ""      }   }    // "int map"   println(getstrfromopt(some(map("a" -> 2, "b" -> 3))))    // "string map"   println(getstrfromopt(some(map("a" -> "2", "b" -> "3"))))  } 

actually, scala uses erasure model of generics java does. no information type arguments maintained @ runtime.

def isintmap(x: any) = x match {    case m: map[int, int] => true    case _ => false } 

for code above, scala compiler can not decide whether m map[int, int] or not. therefore, isintmap(map("a"-> "b")) return true, seems non-intuitive. alert runtime behavior, scala compiler emitted un-checked message.

however, array exception, element type stored element value.

def isintarray(x: any) = x match {   case a: array[string] => "yes"   case _ => "no" }   scala> isintarray(array(3)) res1: string = no  scala> isintarray(array("1")) res2: string = yes 

Comments