Numeric
class instance type has a zero
method that does what you want:
class SumUtil[T: Numeric] extends MathUtil[T] { private var sum: T = implicitly[Numeric[T]].zero override def nextNumber(value: T) { sum = implicitly[Numeric[T]].plus(sum, value) } override def result(): T = sum }
Note that you also need an instance for the plus
method if you are not importing Numeric.Implicits._
, in which case you can use +
. You can also clear the code a bit without using the context-related syntax in this case:
class SumUtil[T](implicit ev: Numeric[T]) extends MathUtil[T] { import Numeric.Implicits._ private var sum: T = ev.zero override def nextNumber(value: T) { sum = sum + value } override def result(): T = sum }
This is exactly equivalent: the context-related version is just syntactic sugar for this implicit argument, but if you need to explicitly use this argument (as you are here for its zero
), I find it cleaner to write desugared.
source share