Search code examples
scalapattern-matchingtype-erasure

Pattern Matching a List[_] in Scala


I have the Following Code

def function1(obj:Any)={

obj match {


        case l:List[Map[String,Any]]=> {
          println("ListMap" + l.toString())
        }
        case l:List[String]=> {
          println ("list String" + l)
        }
        case None =>
      }
}

When I pass a List Of Maps and String to this function, it keeps printing only the first case statement, it doesn't go the second one. Is there anything I'm doing wrong ?


Solution

  • The reason is that both of them are List (the function is just checking the outer dataType and ignoring the inner dataType.
    You can use the following solution for your case and modify as you need.

     def function(obj: Any) : Unit = {
       Try {
         obj.asInstanceOf[List[Map[String, Any]]].map(function2(_))
         println("ListMap")
       }getOrElse (
         Try{
            obj.asInstanceOf[List[String]].map(function2(_))
            println("List of String")
         }getOrElse
           println("do nothing")
         )
     }
    

    The reason for the necessary of function2 is that without transformation the casted datatype is not recognised. You need some transformation in the data you pass to the function anyway

     def function2(obj: Any) = obj match {
       case _ : Map[String, Any] => //do what you want with your map
       case _ : String => //do what you want with your string list
       case _  => // this is not done for now
     }
    

    I hope this is exactly what you are looking for