Calculus5000
Calculus5000

Reputation: 427

Scala: Shift elements in an Array

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

Upvotes: 1

Views: 2450

Answers (1)

insan-e
insan-e

Reputation: 3921

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)...

Upvotes: 5

Related Questions