2
votes

I am Scala beginner and started going through "Programming in Scala". I came across the following code.

for (arg <- args)
println(arg)

In the book it say's arg is of type val and not var. Why is it so.

As per my understanding for each iteration the value of arg is changed, as it holds new value each time it is looped.

Following are my questions

  1. Why is arg val and not var ?
  2. As per Scala if it is val we cannot change the value (Since it is final in Scala)
  3. Also will it create multiple objects for each iteration and how are the objects destroyed after the loop ?

Also i know the difference between var and val in scala. I have gone across this link. What is the difference between a var and val definition in Scala?

1

1 Answers

7
votes

In Scala, a for comprehension is syntax sugar over foreach, map, flatMap and filter combinators. When you write:

for (arg <- args)

The compiler re-writes to:

args.foreach { }

Since foreach introduces a fresh value for each element, you don't actually reassign arg to anything:

args.foreach { arg => // }

For example, if we take a look at the implementation of List.foreach:

@inline final override def foreach[U](f: A => U) {
  var these = this
  while (!these.isEmpty) {
    f(these.head)
    these = these.tail
  }
}

You see that these is a var which is being re-assigned as you iterate the list, so internally the Scala collection library keeps a mutable reference to the list, but from the outside each value of type A exposed to you as a caller via f(these.head) is immutable, so there isn't actually a need to reassign a reference to a value like in a C style for-loop.