在 Scala 中匹配列表 [_] 的模式

Pattern Matching a List[_] in Scala

我有以下代码

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 =>
      }
}

当我将映射列表和字符串传递给此函数时,它只打印第一个 case 语句,而不会打印第二个。我做错了什么吗?

下面的草图呢(类型取决于你的用途):

def f[T](obj : List[T], trans : T => String) = obj.map(trans).mkString

然后你调用f如下:

scala> f[Map[Int,Int]](List(Map(1->2, 3->4), Map(0->0)), _.toList.map( x => (x._1 - x._2).toString).mkString(","))
res5: String = -1,-10

scala> f[String](List("abc","def","ghi"), x => x.reverse)
res6: String = cbafedihg

原因是它们都是List(函数只是检查outer dataType而忽略了inner dataType
您可以针对您的情况使用以下解决方案并根据需要进行修改。

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

之所以需要 function2 是因为没有 transformation 就无法识别 casted datatype。无论如何,您传递给 function 的数据中需要一些 transformation

 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
 }

希望这正是您要找的