Value assignment inside for-loop in Scala

后端 未结 2 1518
终归单人心
终归单人心 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:27

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

提交回复
热议问题