how can i do to grouped two list that contains different case classes, but on both classes have same field:
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)
error: value a is not a member of Product with Serializable
thanks
Fearing not the pattern match:
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)))
Crudely but as requested:
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)))
or
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)))
Is the resulting collection especially well-typed?
Update:
(i++j) groupBy (_.asInstanceOf[{ def a: Long }].a)
I wonder if the IDE has a refactor, "convert to underscore"?
You can also use the Product
trait to extract the first item:
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)))
i solved it using this:
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
then:
val c = (X++Y).groupBy(_.a)
thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.