如果我有一个像这样的 List[Any] 形式的列表
val list = List(List(1, 1), 2, List(3, List(5, 8)))
然后我如何编写区分的匹配语句
- 任何非列表类型的单个元素(即上面的 2)
- 列表元素(即上面的 List(1,1) 和 List(3, List(5, 8))
或者在伪scala中
list match {
case x:"single non-list element" => // do something with single element x
case y:"where y is a list" => // do something with list y
}
通常的 head::tails 匹配不起作用,因为 head 可以是包含其他列表的 Any 类型。
最佳答案
list foreach {
_ match {
case x:List[_] => // list
case _ => // anything else
}
}
我想应该可以吧
关于scala - 匹配列表列表中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8146242/