title: Swapping values in an array using Pattern Matching in Scala
body: <p>I am trying to solve the following problem from <a href="https://rads.stackoverflow.com/amzn/click/com/0321774094" rel="nofollow noreferrer" rel="nofollow noreferrer">Scala for the impatient</a>. The question is as follows:</p>
  
  <blockquote>
    <p>Using pattern matching, write a function swap that swaps the first two elements of an array provided its length is at least two.</p>
  </blockquote>
  
  <p>My solution is:</p>
  
  <pre><code>def swap(sArr:Array[Int]) = sArr.splitAt(2) match { 
                                 case (Array(x,y),Array(z)) =&gt; Array(y,x,z)
                                 case (Array(x,y),Array()) =&gt; Array(y,x)
                                 case _ =&gt; sArr
                              }
  </code></pre>
  
  <p>My problem is with the first case statement. I think it would pattern-match something like <code>(Array(1,2),Array(3))</code> whereas I intend it to pattern-match <code>(Array(1,2),Array(3,4,5.....))</code></p>
  
  <p>Can somebody point out how that would be possible.</p>
  
  <p>Thanks </p>