If you want it to be as fast as possible, which I assume is the case where the shift operation is then you should use a while loop:
var i = password.length() while (i != 0) { // some code i >>>= 1 }
This is one of the few cases where Java is more compact than Scala with the same operation.
You can also use tail recursion:
final def passwordStuff(password: Password)(i: Int = password.length): Whatever = { if (i != 0) { // Some code passwordStuff(password)(i >>> 1) } }
which will compile into something at the same speed as the while loop (anyway, anyway).
source share