0

In a book on Scala programming I came around this example. They say that this example of imperative code

def printArgs(args: Array[String]): Unit = {
    var i = 0
    while (i < args.length) {
        println(args(i))
        i += 1
    }
}

Can be "translated" into functional style like that:

def printArgs(args: Array[String]): Unit = {
    for (arg <args)
        println(arg)
}

But to me these two codes are not absolutelly identical, the second one completelly missing variable "i". And so if I want to print it along with value of string I cannot do it in the second example, or can I? How?

henry
  • 607
  • 2
  • 8
  • 15
  • 5
    `for ((arg, i) < args.zipWithIndex)` ... – senia Oct 30 '14 at 14:53
  • 3
    There must be a duplicate of this somewhere.. – Michael Zajac Oct 30 '14 at 14:53
  • To elaborate a bit, in your first example, the only purpose of the index is book-keeping. It doesn't factor into the output of the function or into its side-effect (printing to screen). Speaking of side-effects, I wouldn't really consider the second block exemplary "functional" code, as purely functional code typically eschews side effects. It's really just showing using an iterator pattern instead of explicit indexing. The advantage is that there's less that can go wrong and your code is more concise. I haven't written a for loop with a counter in a long time for this reason. – acjay Oct 30 '14 at 18:58

0 Answers0