0

I'm trying create a histogram class by extending a mutable hash map, the Key type could be anything while the counter type has to be a number(int, float, long etc). Also I'd like the default value to be zero.

I was able to implement it using this piece of code:

 class histogram[KEY, COUNT: Numeric] extends scala.collection.mutable.HashMap[KEY, COUNT] {

     /** Returns zero if a key does not exist*/
     override def default(key: KEY) = {
         zero()
     }

     def zero()(implicit n: Numeric[COUNT]) = {
         n.zero
     }
}

I can't find a better way to generate a zero of type COUNT, can't move (implicit n: Numeric[COUNT]) after default(key: KEY) since it would no longer override.

Is there a better way to implement it?

How can I create an instance of scala.Numeric[COUNT] without using the (implicit n: Numeric[COUNT]) ?

markiz
  • 265
  • 1
  • 7

1 Answers1

4

The syntax A: TypeClass (also known as context-bound) is a short cut for asking for an implicit parameter implicit aTpe: TypeClass[A]. You can recover that parameter in the first notation using implicitly[TypeClass[A]], or just use the latter syntax.

class histogram[KEY, COUNT: Numeric] 
  extends scala.collection.mutable.HashMap[KEY, COUNT] {

  def zero() = implicitly[Numeric[COUNT]].zero
}

or (equivalent)

class histogram[KEY, COUNT](implicit numeric: Numeric[COUNT]) 
  extends scala.collection.mutable.HashMap[KEY, COUNT] {

  def zero() = numeric.zero
}
0__
  • 66,707
  • 21
  • 171
  • 266