我试图使重载的加法运算符与集合的sum
方法一起工作。例如,对于
final case class Probability(val value: Double) {
def +(that: Probability): Probability =
Probability(this.value + that.value)
}
List(Probability(0.4), Probability(0.3)).sum
我收到以下错误消息:
Error:(6, 109) could not find implicit value for parameter num:
Numeric[A$A42.this.Probability]
def get$$instance$$res0 = /* ###worksheet### generated $$end$$ */
List(Probability(0.4), Probability(0.3)).sum;}
Error:(6, 109) not enough arguments for method sum:
(implicit num: Numeric[A$A42.this.Probability])A$A42.this.Probability.
Unspecified value parameter num.
def get$$instance$$res0 = /* ###worksheet### generated $$end$$ */
List(Probability(0.4), Probability(0.3)).sum;}
我认为这必须与implicit
做一些事情(错误消息明确指出),但是我不知道应该在哪里定义或添加它(在案例Probability
中,它的维数对象,还是sum
之后?),或者它的外观。
答案 0 :(得分:3)
Sum方法与类型类Numeric [T]一起使用,因此,如果要在自己的“数字类型”上调用sum,则需要定义Numeric [Probability]的实例。
放置自定义类型类定义的最佳位置是对象伴侣。
object Probability {
implicit val probabilityNumberic = new Numeric[Probability] {
def plus(x: Probability, y: Probability): Probability = ???
def minus(x: Probability, y: Probability): Probability = ???
def times(x: Probability, y: Probability): Probability = ???
def negate(x: Probability): Probability = ???
def fromInt(x: Int): Probability = ???
def toInt(x: Probability): Int = ???
def toLong(x: Probability): Long = ???
def toFloat(x: Probability): Float = ???
def toDouble(x: Probability): Double = ???
def compare(x: Probability, y: Probability): Int = ???
}
}
或者,如果您不想定义Numeric [T]实例,或者希望将概率作为结果,则可以使用reduce代替sum。
List(Probability(0.4), Probability(0.3)).reduce(_ + _)
或reduceOption(如果列表可以为空)。
关于定义Numeric[Probability]
的位置,必须考虑隐式对象的范围。通常在对象协同对象上定义默认实现,但是可以在sum调用之前,通过导入或您可以显式使用它。这取决于您的需求。