如何在 Scala 中返回迭代器?
我必须做什么才能从方法/类返回迭代器?如何将这一特征添加到类中?
What must I do in order to be able to return an Iterator from a method/class ? How would one add that trait to a class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以扩展 Iterator,这需要您实现
next
和hasNext
方法:但是,如果扩展 Iterable,它要求您实现
elements
(或 2.8 中的iterator
):常见的习惯用法似乎是将迭代器公开给某些私有集合,如下所示:
You can extend Iterator, which will require that you implement the
next
andhasNext
methods:But, you will get more flexibility if you extend Iterable, which requires you implement
elements
(oriterator
in 2.8):A common idiom seems to be to expose an iterator to some private collection, like this:
对于方法,只需 yield:
For a method, just yield:
这两个答案从下面的帖子中得到了帮助,并感谢@Dima。
如何为现有单链表实现迭代器?
为什么这个可迭代实现会产生 stackoverflow?
假设您有一个类链表。而要求是打印列表中的所有元素。
现在让我们为这个类实现迭代器。
在迭代器实现中,一旦 ptr 到达末尾,它就无法前进。可迭代的实现解决了这个问题。
These two answers had help from the posts below and thanks @Dima.
How do I implement an iterator for an existing singly linked list?
why does this iterable implementation produce a stackoverflow?
Lets assume you have a class linked list. And the requirement is to print all the elements in the list.
Now Lets implement iterator to this class.
In the iterator implementation, once ptr reached the end, it could did not advance back. Iterable implementation solves this.