2017-03-03 72 views
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() 
}) 

但感觉应该有这样使用键初始MapgroupBy返回一个更好的方式。

回答

3

A in case (A, alist)指的是伴侣对象A,其类型为A.type。这就是为什么你会收到错误信息。如果你想匹配类元数据,你应该参考classOf[A]。也没有理由使用match,因为您可以与map进行模式匹配。

y.map { 
    case (c, alist) if(c == classOf[A]) => println("found me some As") 
    case (c, blist) if(c == classOf[B]) => println("not As") 
}