It'd be better to rewrite this using a while loop, since while loops perform much better than for loop in Scala.