0
我有一个元素列表,并希望按类对它们进行分组,然后处理结果。scala groupBy类然后映射结果
trait H
case class A(x: Int) extends H
case class B(x: Int) extends H
val x = List(A(1),B(2),B(3))
val y = x.groupBy(_.getClass)
y.map(_ match {case (A, alist) => println("found me some As")
case (B, blist) => println("not As")})
很不幸,这会产生这样的错误:
<console>:17: error: pattern type is incompatible with expected type;
found : A.type
required: Class[_ <: Product]
Note: if you intended to match against the class, try `case _: A`
y.map(_ match {case (A, alist) => println("found me some As")
也就是说,我似乎无法找到正确的方式做匹配的情况下,当项目被匹配是类不仅仅是一个实例。
的部分解决方案如下:
val z = y.map(_ match {case (atype, alist) => alist })
z.map(_ match {
case alist if alist.head.isInstanceOf[A] => alist
case blist => List()
})
但感觉应该有这样使用键初始Map
从groupBy
返回一个更好的方式。