Scala for循环.简洁地获取索引 [英] Scala for-loop. Getting index in consice way
本文介绍了Scala for循环.简洁地获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这段代码中,我想增加index
到每个yield
ing结果中.
In this code I want to increment index
to put it to each yield
ing result.
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
为什么我不能更改index
?那么,为了简洁起见,实现此逻辑的最佳方法是什么?
Why I can not change index
? And what the best way to implement this logic then, trying to be concise?
推荐答案
大多数类似序列的集合中的zipWithIndex
方法将为您提供从零开始的索引,并随每个元素递增:
The zipWithIndex
method on most sequence-like collections will give you a zero-based index, incrementing with each element:
for ((str, index) <- splitToStrings(text).zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
这篇关于Scala for循环.简洁地获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文