0

I am very new to scala and am trying to print the char at each index in a string as follows —

val p = "each other we love"
p.foreach((x, i) => println(s"CHAR@$i $x"))

I assumed that the second argument would be the index of the character which obviously isn't true and thus getting a type error.

tusharmath
  • 10,622
  • 12
  • 56
  • 83

1 Answers1

0

You need to use zipWithIndex, index is not supplied to you during normal traversal:

p.zipWithIndex.foreach { case (x, i) => println(s"CHAR@$i $x") }
Suma
  • 33,181
  • 16
  • 123
  • 191