title: Type mismatch for generic Integral in Scala
body: <p>I am trying to code a decoder for <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/" rel="nofollow">Base64 Variable Length Quanties</a> in  Scala.</p>
  
  <p>(Base64 VLQ encodes a sequences of signed integers. The encoding has no restrictions on the range of integers encoded.)</p>
  
  <p>For my current use case, I kow that <code>Seq[Int]</code> will suffice. Of course, I'd like to make it so I can decode to <code>Seq[Long]</code>, or <code>Seq[BigInteger]</code>, or even something like <code>Seq[Short]</code>.</p>
  
  <p>The algorithm is exactly the same, just with different types.</p>
  
  <p>Generics to the rescue! (Or so I thought.) </p>
  
  <hr>
  
  <pre><code>object Base64Vlq {
    val continuationMask = (1 &lt;&lt; 5).toByte
    val signMask = 1.toByte
  
    def decode[T &lt;: Integral[T]](bytes: Seq[Byte]): Seq[T] = {
      val result = scala.collection.mutable.ListBuffer[T]()
      bytes.foldLeft((0, 0)) { (arg, byte) =&gt;
        val (value, n) = arg
        if((byte &amp; continuationMask) == 0) {
          val newValue = value + (byte / 2 &amp; ~continuationMask) &lt;&lt; 5 * n
          result += (if((byte &amp; signMask) == 0) { newValue } else { -newValue })
          (0, 0)
        } else {
          (value + (byte &amp; ~continuationMask).toInt &lt;&lt; 5 * n, n + 1)
        }
      }
      result
    }
  }
  </code></pre>
  
  <p>This has a compile error: </p>
  
  <pre><code>error: type mismatch;
  found   : newValue.type (with underlying type Int)
  required: T
         result += (if((byte &amp; signMask) == 0) { newValue } else { -newValue })
  </code></pre>
  
  <p>I can see the problem: <code>0</code>, <code>value</code>, and <code>newValue</code> are all of type <code>Int</code>.</p>
  
  <p>What can I do to fix this?</p>
  
  <hr>
  
  <p>FYI, this is how I would do the same thing in C++, with only a couple more lines of code.</p>
  
  <pre><code>#include &lt;vector&gt;
  
  template&lt;typename T&gt;
  std::vector&lt;T&gt; decode(std::vector&lt;char&gt; bytes) {
      char continuationMask = 1 &lt;&lt; 5;
      char signMask = 1;
      vector&lt;T&gt; result;
      int n(0);
      T value(0);
      for(auto it = bytes.begin(); it != bytes.end(); it++) {
          if(*it &amp; continuationMask) {
              value += (*it &amp; ~continuationMask) &lt;&lt; 5 * n;
              n++;
          } else {
              value += (*it / 2 &amp; ~continuationMask) &lt;&lt; 5 * n;
              result.push_back(*it &amp; signMask ? -value : value);
              value = 0;
              n = 0;
          }
      }
      return result;
  }
  </code></pre>
  
  <hr>
  
  <p>P.S. As a side note, if anyone knows of a Java/Scala based Base64 VLQ implementation in public Maven/Ivy repos, even if it's not generic, I'd appreciate knowing it.</p>