Value assignment inside for-loop in Scala

后端 未结 2 1479
北荒
北荒 2021-02-20 01:36

Is there any difference between this code:

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

and:

2条回答
  •  不要未来只要你来
    2021-02-20 02:10

    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)
       ...
    }
    

提交回复
热议问题