Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Numeric init with constant 0

Tags:

numeric

scala

Lets I have a utility class called MathUtil.

and it looks like this .

abstract class MathUtil(T:Numeric){
   def nextNumber(value:T)
   def result():T
}

Lets I subclass it this way

class SumUtil[T:Numeric] extends MathUtil[T]{
   private var sum:T = 0
   override def nextNumber(value:T){
     sum = sum + value
   }
   override def result():T = sum
}

I have a problem with the statement

private var sum:T = 0

Now , I have to initialize to sum to 0. I would guess any numeric to have a way to represent 0. Im pretty new to scala. How do I solve this issue ?

like image 252
questionersam Avatar asked Jun 22 '12 19:06

questionersam


1 Answers

The Numeric type class instance 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 the instance for the plus method, unless you import Numeric.Implicits._, in which case you can use +. You can also clean the code up a bit by not using the context bound 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 bound version is just syntactic sugar for this implicit argument, but if you need to use that argument explicitly (as you do here, for its zero), I find it cleaner to write the desugared version.

like image 92
Travis Brown Avatar answered Sep 22 '22 01:09

Travis Brown