问题描述
我有几个使用 count
字段的案例类。默认情况下它是1,并且我在代码中减少了对重复数据进行分组并对其进行求和的总和,以查找每个对象的数量。例如:
I have several case classes with a count
field. It's 1 by default, and I have a reduce in my code that groups duplicates and sums that value to find the number of each object. E.g.:
case class Person(name: String, count = 1)
personList.groupBy(_.name).reduce((x,y) => x.copy(count = x.count + 1))
我在几个case类中有这个逻辑,因为我的逻辑比上面的例子复杂一点,所以我想创建一个泛型合并函数。
I have this logic in several case classes, and since my logic is a bit more complicated than the example above I want to create a generic merging function.
我使用 count
字段创建了一个密封特质
。然后我改变了我的case类以扩展它,例如:
So I've created a sealed trait
with a count
field. I've then changed my case classes to extend from this, e.g.:
case class Person(name: String, override val count) extends Countable
到目前为止,那么好。
然而,我无法弄清楚如何声明我的 merge
函数,以便它只接受扩展 Countable 。因此,它无法找到
copy
方法。
However, I can't work out how to declare my
merge
function so that it only accepts case classes that extend Countable
. Because of that, it can't find the copy
method.
以下是我的:
Here's what I have:
def merge[T <: Countable](f: T => Seq[String])(ms: Seq[T]): Vector[T] =
ms.groupBy(x => f(x).mkString("_")).mapValues(_.reduce { (x,y) =>
x.copy(count = x.count + 1) // can't find `copy`
}).values.toVector
是否有一个类型类型可以包含它,意味着类型有一个
copy
方法(或者是一个case类)使用Scala 2.11.7?
Is there a typeclass that I can also include that means a type has a
copy
method (or is a case class) using Scala 2.11.7?
更新:
Countable
特质是:
Countable
trait is:
sealed trait Countable {
def timesSeen: Long = 1
}
推荐答案
你是如何定义你可数特质的。
以下代码片段适用于我:
How did you defined you Countable trait.Following snippet works fine for me:
trait Countable[Z] {
def count: Int
def copy: Z
}
case class Person(name: String, override val count: Int) extends Countable[Person] {
override def copy: Person = this
}
def merge[T <: Countable[T]](f: T => Seq[String])(ms: Seq[T]): Vector[T] = {
val r = ms.groupBy(x => f(x).mkString("_")).mapValues(_.reduce { (x, y) =>
x.copy
}).values.toVector
r
}
这篇关于斯卡拉泛型:如何声明一个类型必须是一个案例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!