1

I'm getting used to the various data structures in Scala and I've noticed that this function (contrived example), which is supposed to move every character in the mutable array to the right by one, has no effect on the array:

  def shiftRight(str: String): Array[Char] = {
    val chars = str.toCharArray
    for(i <- chars.length - 1 until 0) chars(i) = chars(i - 1)
    chars
  }
  println(shiftRight("ABCD").mkString)

which produces the result

ABCD

not the expected

AABC
2
  • until 0 by -1 Commented Dec 26, 2016 at 15:02
  • Or even better to use more explicit i <- Range(start = chars.length - 1, end = 0, step = -1) Commented Dec 26, 2016 at 15:12

1 Answer 1

5

Default step for range is one. See class Range here and implicit that gets you to it here.
Instead of

for(i <- chars.length - 1 until 0)...

you need:

for(i <- chars.length - 1 until 0 by -1)...
Sign up to request clarification or add additional context in comments.

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.