4

I need to convert some Java code to Scala. I have such source. How to rewrite it in Scala? Question may be simple. But it match harder then for(i <- 1 until 10) {} examples in documentation.

for (int i = password.length(); i != 0; i >>>=1)
  { some code }

King regards, Alexey

4 Answers 4

6

If you want it to be as fast as possible--which I am assuming is the case given the shift operation--then you should use a while loop:

var i = password.length()
while (i != 0) {
  // some code
  i >>>= 1
}

It's one of the few cases where Java is more compact than Scala given the same operation.

You could 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 of the same speed as the while loop (in almost every case, anyway).

Sign up to request clarification or add additional context in comments.

Comments

2

If you seek for exotic functional way you can write something like this:

Stream.iterate(password.length)(i => i >>> 1).takeWhile(0!=)

It lazily performs the following actions: takes password length as initial value, applies { => i >>> 1 } to it, passes it to the next iteration, applies ... passes, ...

Then I've scoped computation, limiting it to only thoose values that are not equals to 0.

Comments

1

i >>>= 1 is equivalent to i /= 2 for positive integers.

Combining this knowledge with the answers to Incrementing the for loop (loop variable) in scala by power of 5 you should be set.

1 Comment

Thank you very much for link. I added it to my bookmarks. Very useful.
0

didnt know the >>>= operator. Let's try to be a little more functional, foreach takes a function A => Unit, in this case A is Int

def breakdownBy2(from:Int):List[Int] = if(from == 0) Nil else List(from) ++  breakdownBy2(from/2)
breakdownBy2(passoword.length).foreach(println(_))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.