如何对包含不同案例类的两个列表进行分组,但两个类都有相同的字段:
case class X(a:Long, b:Long, c:Long, d:Long)
case class Y(a:Long, e:Long, f :Long)
val i = List(X(10,10,8,8))
val j = List(Y(10,10,8))
val joined = a++b
joined.groupBy(_.a)
错误:值a不是具有Serializable的产品的成员
感谢
答案 0 :(得分:6)
不要模式匹配:
scala> val joined = (i++j) groupBy { case x: X => x.a case y: Y => y.a }
joined: scala.collection.immutable.Map[Long,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))
粗略但按要求:
scala> val joined = ((i++j).asInstanceOf[List[{ def a: Long }]]) groupBy(_.a)
warning: there were 1 feature warning(s); re-run with -feature for details
joined: scala.collection.immutable.Map[Long,List[AnyRef{def a: Long}]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))
或
scala> val joined = (i++j) groupBy { case x => x.asInstanceOf[{ def a: Long }].a }
warning: there were 1 feature warning(s); re-run with -feature for details
joined: scala.collection.immutable.Map[Long,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))
生成的集合特别好吗?
更新
(i++j) groupBy (_.asInstanceOf[{ def a: Long }].a)
我想知道IDE是否有重构,“转换为下划线”?
答案 1 :(得分:0)
您还可以使用Product
特征提取第一项:
scala> val joined= (i++j).groupBy(_.productIterator.toList.head)
joined: scala.collection.immutable.Map[Any,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))
答案 2 :(得分:0)
我用这个解决了它:
trait genericClass{
def a:Long
}
case class X(override val a:Long, b:Long, c:Long, d:Long) extends genericClass
case class Y(override val a:Long, e :Long, f :Long) extends genericClass
然后:
val c = (X++Y).groupBy(_.a)
感谢