Reputation: 3
def move(s: String) {
var moveList: List[Char] = s.toList
moveList.foreach(moveList(_) match {
case 'r' => ar()
case 'l' => al()
case 'u' => au()
case 'd' => ad()
})
}
my current function leads to the error: java.lang.IndexOutOfBoundsException: 114. If you could please help it would be greatly appreciated, thank you.
Upvotes: 0
Views: 48
Reputation: 22840
moveList.foreach(moveList(_)
this is the same as moveList(char => moveList.apply(char.toInt))
that should give you an idea of what is wrong.
In any case, the point of a foreach
is to take each element of the collection and apply that function to each of them. That is why the name FOR EACH. Not to access the elements by some index.
Also, a String is already an iterable, thus your code can be simplified to:
def move(s: String): Unit =
s.foreach {
case 'r' => ar()
case 'l' => al()
case 'u' => au()
case 'd' => ad()
case c => println(s"Bad action: ${c}")
}
PS: Try to avoid vars, especially useless ones.
Force yourself to use vals everywhere.
Upvotes: 2