scala groupBy 类然后映射结果 [英] scala groupBy class then map the results

查看:24
本文介绍了scala groupBy 类然后映射结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of elements, and want to group them by class and then process the results.

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

不幸的是,这会产生如下错误:

Unfortunately this produces errors like:

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

也就是说,当被匹配的项目一个类而不仅仅是一个实例时,我似乎无法找到进行大小写匹配的正确方法.

That is, I can't seem to find the proper way to do case matching when the item being matched is a class not just an instance of one.

部分解决方案如下:

val z = y.map(_ match {case (atype, alist) => alist })
z.map(_ match {
  case alist if alist.head.isInstanceOf[A] => alist 
  case blist => List()
})

但感觉应该有更好的方法来使用从 groupBy 返回的初始 Map 的键.

But it feels like there should be a better way of doing this using the keys to the initial Map returned from groupBy.

推荐答案

Acase (A, alist)中指的是A<的伴随对象/code>,类型为 A.type.这就是您收到该错误消息的原因.如果你想匹配类元数据,你应该参考classOf[A].也没有理由使用 match,因为您已经可以使用 map 进行模式匹配.

A in case (A, alist) refers to the companion object of A, which has the type A.type. That's why you're getting that error message. If you want to match against the class meta data, you should refer to classOf[A]. There's also no reason to use match, as you can pattern match with map already.

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

这篇关于scala groupBy 类然后映射结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆