我有一个代码(sentences在iterator这里):
def count() = {
var count = 0
for(sentence <- sentences.toStream) count += sentence.words.size
count
}
并测试:
// first
val wordCount1 = wordCounter.count()
wordCount1 must_== 10
// second time - should be same result
val wordCount2 = wordCounter.count()
wordCount2 must_== 10 // fails: result is 0
最后一次测试失败:
'0' is not equal to '10'
Expected :10
Actual :0
但是由于我sentences.toStream在上面的代码中使用,我想stream它是(理论上我可以重用它)。
问:为什么会失败?
编辑:
我希望这toStream会有所帮助。就像这里Stream描述的那样:(...“您可以多次遍历相同的内容”...)。就像我从不接触迭代器一样,我处理的是流。
但是我得到了..sentences.toStream 用完 sentence-iterator了,所以我不能再使用它了。我只是期望在做toStream的时候iterator做一个逻辑,比如在不触及迭代器本身的情况下将流“链接”到迭代器。行..