title: recursively convert Map[Int, Map[Int, X]] to Array[Array[X]]
body: <p>I am trying to write a function that converts between Maps with integer keys to the corresponding arrays. I have the base case done, but am trying to write the recursive case (i.e. multi-dimensional arrays: converting Map[Int, Map[Int, X]] to Array[Array[X]]).</p>
  
  <p>This task arose out of the need to construct an array from a stream without knowing how large the array will be in advance, allowing for the possibility of elements to come off the stream in random order and the possibility of duplicate elements coming off the stream.</p>
  
  <p>I have a function that does it:</p>
  
  <pre><code>def toArrayHard[X:ClassManifest](x:scala.collection.Map[Int, X]):Array[X] =
  {
      if (x.size == 0) new Array(0)
      else 
      {
          val max:Int = 1 + x.keys.max
  
          val a:Array[X] = new Array(max)
  
          var i = 0
          while (i &lt; max)
          {
              a(i) = x(i)
              i += 1
          }
          a
      }
  }
  </code></pre>
  
  <p>Note, I'm aware that the code fails if the map contains key k but doesn't contain key i where 0 &lt;= i &lt; k. This is okay for my purposes.</p>
  
  <p>Now I'm looking to do the same for arbitrarily deep multi-dimensional arrays.
  For example, converting between Map[Int, Map[Int, X]] to Array[Array[X]]. Unfortunately, I am getting tripped up by the types. Using the above as a base case, here's what I have so far:</p>
  
  <pre><code>def toArrayHardRec[X:ClassManifest](x:scala.collection.Map[Int, X]):Array[X] =
  {
      import scala.collection.Map
  
      if (x.size == 0) new Array(0)
      else 
      {
          x match
          {
              case t:Map[Int, Map[Int, Y]] forSome { type Y } =&gt;
              {
                  val f0 = t.mapValues{m =&gt; toArrayHardRec[Map[Int, Y]](m)}
                  toArrayHard(f0)
              }
              case _ =&gt; toArrayHard(x)
          }
      }
  }
  </code></pre>
  
  <p>This is the error that I get:</p>
  
  <blockquote>
    <p>'=>' expected but 'forSome' found.</p>
  </blockquote>
  
  <p>Since this is an educational pursuit, any feedback is greatly appreciated. Specifically, I would appreciate any code critiques of my awfully java-looking code, existing scala functions that do the same thing, or suggestions for an alternative way to build these arrays.</p>