title: Scala reduceByKey function - use any type that has + method
body: <p>I am writing a simple function called <code>reduceByKey</code> that takes a collection of (key, numeric) pairs and returns reduced collection by key. </p>
  
  <pre><code>  def reduceByKey[K](collection: Traversable[Tuple2[K, Int]]) = {    
      collection
        .groupBy(_._1)
        .map { case (group: K, traversable) =&gt; traversable.reduce{(a,b) =&gt; (a._1, a._2 + b._2)} }
    }
  </code></pre>
  
  <p>This currently works for: </p>
  
  <pre><code>scala&gt; val col = List((("some","key"),100), (("some","key"),100), (("some","other","key"),50))
  col: List[(Product with Serializable, Int)] = List(((some,key),100), ((some,key),100), ((some,other,key),50))
  
  scala&gt;  reduceByKey(col)      
  res42: scala.collection.immutable.Map[Product with Serializable,Int] = Map((some,key) -&gt; 200, (some,other,key) -&gt; 50)
  </code></pre>
  
  <p>But, I as soon as I want to use non-Int type for numeric, it fails miserably, as it expects an <code>Int</code>.</p>
  
  <pre><code>scala&gt; val col = List((("some","key"),100.toDouble), (("some","key"),100.toDouble), (("some","other","key"),50.toDouble))
  col: List[(Product with Serializable, Double)] = List(((some,key),100.0), ((some,key),100.0), ((some,other,key),50.0))
  
  scala&gt; reduceByKey(col)
  &lt;console&gt;:13: error: type mismatch;
   found   : List[(Product with Serializable, Double)]
   required: Traversable[(?, Int)]
                reduceByKey(col)
                                  ^
  </code></pre>
  
  <p>Of course, I could make different methods for different types, but that would be silly. Basically I want my method to work with any type that has <code>+</code> method defined. That would be <code>Double</code>, <code>Float</code>, <code>Long</code>, <code>Int</code> and <code>Short</code>.</p>
  
  <ol>
  <li>At first, I thought I could use structural type instead of Int. But that would mean the structural type would need to reference itself in order to be of any use.</li>
  <li>I looked into <a href="http://www.scala-lang.org/api/2.9.2/scala/math/Numeric.html">Numeric</a> trait that I think could be useful. It encapsulates the + methods of all numeric types. However, I am not sure how to use it in my case. I dont want force the user of my function to wrap values in Numeric just for my function to work. The function itself should somehow implicitly wrap it up and invoke <code>Numeric.plus</code>.</li>
  </ol>
  
  <p>I am open to any suggestions as how to solve this.</p>