且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Scala中的索引进行高效迭代

更新时间:2023-01-23 08:26:58

比遍历两次要糟糕得多,它创建了一对中间数组。
您可以使用查看。当您执行 collection.view 时,您可以将后续调用视为在迭代期间懒惰地执行。如果你想回到一个完全实现的完全集合,你最后会调用 force 。这将是无用的和昂贵的。所以将代码更改为

Much worse than traversing twice, it creates an intermediary array of pairs. You can use view. When you do collection.view, you can think of subsequent calls as acting lazily, during the iteration. If you want to get back a proper fully realized collection, you call force at the end. Here that would be useless and costly. So change your code to

for((x,i) <- xs.view.zipWithIndex) println("String #" + i + " is " + x)