Alex Rivera | Logout

Value assignment inside for-loop in Scala

Asked 2011-06-22T23:11:57.227
12

Is there any difference between this code:

    for(term <- term_array) {
        val list = hashmap.get(term)
        ...
    }

and:

    for(term <- term_array; val list = hashmap.get(term)) {
        ...
    }

Inside the loop I'm changing the hashmap with something like this

hashmap.put(term, string :: list)

While checking for the head of list it seems to be outdated somehow when using the second code snippet.

Edit
Report

1 Answer

8

Instantiating variables inside for loops makes sense if you want to use that variable the for statement, like:

for (i <- is; a = something; if (a)) {
   ...
}

And the reason why your list is outdated, is that this translates to a foreach call, such as:

term_array.foreach {
   term => val list= hashmap.get(term)
} foreach {
  ...
}

So when you reach ..., your hashmap has already been changed. The other example translates to:

term_array.foreach {
   term => val list= hashmap.get(term)
   ...
}
answered 2011-06-23T02:22:00.463

Your Answer