你如何在Scala中返回迭代器? [英] How do you return an Iterator in Scala?

查看:202
本文介绍了你如何在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?

推荐答案

您可以扩展迭代器,这将要求你实现 next hasNext 方法:

You can extend Iterator, which will require that you implement the next and hasNext methods:

  class MyAnswer extends Iterator[Int] {
    def hasNext = true
    def next = 42
  }

但是,如果你扩展 Iterable ,你将获得更大的灵活性,这需要你实现元素(或2.8中的 iterator ):

But, you will get more flexibility if you extend Iterable, which requires you implement elements (or iterator in 2.8):

  class MyAnswer extends Iterable[Int] {
    def iterator = new Iterator[Int] {
      def hasNext = true
      def next = 42
    }
  }

一个常见的习惯用法似乎是将迭代器暴露给某些人私人收藏,像这样:

A common idiom seems to be to expose an iterator to some private collection, like this:

  class MyStooges extends Iterable[String] {
    private val stooges = List("Moe", "Larry", "Curly")
    def iterator = stooges.iterator
  }

这篇关于你如何在Scala中返回迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆