在Scala中的for循环中赋值 [英] Value assignment inside for-loop in Scala
本文介绍了在Scala中的for循环中赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码是否有区别:
$ b
Is there any difference between this code:
for(term <- term_array) {
val list = hashmap.get(term)
...
}
和: (term
and:
for(term <- term_array; val list = hashmap.get(term)) {
...
}
在循环内部,我正在使用类似这样的方式更改hashmap
Inside the loop I'm changing the hashmap with something like this
hashmap.put(term, string :: list)
在检查 list
的头部时,使用第二个代码片段似乎已经过时了。
While checking for the head of list
it seems to be outdated somehow when using the second code snippet.
推荐答案
c $ c>语句,如:
pre $ for(i < - is; a = something; if(a)){
...
}
for (i <- is; a = something; if (a)) {
...
}
以及您的列表过期的原因,是这个转换为 foreach
调用,如:
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 {
...
}
所以当你到达...时,你的hashmap已经被改变了。另一个例子转换为:
So when you reach ..., your hashmap has already been changed. The other example translates to:
term_array.foreach {
term => val list= hashmap.get(term)
...
}
这篇关于在Scala中的for循环中赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文