Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala groupBy类然后映射结果_Scala_Types - Fatal编程技术网

scala groupBy类然后映射结果

scala groupBy类然后映射结果,scala,types,Scala,Types,我有一个元素列表,希望按类对它们进行分组,然后处理结果 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, bl

我有一个元素列表,希望按类对它们进行分组,然后处理结果

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

但是感觉应该有更好的方法,使用
groupBy
a
返回的初始
Map
,在
案例(a,alist)
指的是
a
的伴生对象,其类型为
a.type
。这就是你收到错误信息的原因。如果要与类元数据进行匹配,应参考[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")
}

A
案例(A,alist)
中,A指的是
A
的伴生对象,其类型为
A.type
。这就是你收到错误信息的原因。如果要与类元数据进行匹配,应参考[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")
}