Compare ZIP codes, disregarding leading zeros I have a function that compares ZIP codes. It also has to handle cases where the input ZIP code be missing leading zeros, have extraneous leading zeros. This is what I've come up with. I don't have any issues with it. But since it's in Scala, I feel there must be a more functional way to write this. 

My only functional thought (outside of the digit validation) is to insert them into a collection, then filter the collection by length != 5, and then attempt to fix them. 

Here's my imperative, stateful version.

  def compareZip(first: String, second: String): Boolean = {
    var firstTmp: String = null
    var secondTmp: String = null
    if(!first.forall(_.isDigit) || !second.forall(_.isDigit)) false
    else if (first.length == ZIPCODE_LENGTH &amp;&amp; first.length == second.length) {
      first equals second
    }
    else {
      if (first.length &gt; ZIPCODE_LENGTH) {
        firstTmp = first takeRight ZIPCODE_LENGTH
      }
      else if (first.length &lt; ZIPCODE_LENGTH) {
        firstTmp = ZERO_STR * (ZIPCODE_LENGTH - first.length) + first
      }
      else firstTmp = first

      if (second.length &gt; ZIPCODE_LENGTH) {
        secondTmp = second takeRight ZIPCODE_LENGTH
      }
      else if (second.length &lt; ZIPCODE_LENGTH) {
        secondTmp = ZERO_STR * (ZIPCODE_LENGTH - second.length) + second
      }
      else secondTmp = second
      firstTmp equals secondTmp
    }
  }
The title of your post is


  Compare ZIP codes, disregarding leading zeros


The solution is simple -- just drop the leading zeros.  Then you can compare the strings directly.

This leads us to something like this:

def compareZip(first: String, second: String): Boolean = {
  first.dropWhile(c =&gt; c == '0') == second.dropWhile(c =&gt; c =='0')
}


If you want, you can factor out the common lambdas.

There's no need to do anything more complicated than that.  "Fixing" the zipcode only makes things more complicated.  And, since the result never leaves the comparison function anyway, all that work is wasted.