Iterator是Scala中的集合吗?

时间:2018-06-22 06:20:16

标签: scala collections

我对Scala中的Iterator感到困惑,这是一个Collection还是一种逐个访问Collection元素的方法?因此,如果它不是Collection,那么我们如何将Iterator用作Iterator(“ a”,“ number”,“ of”,“ words”)? 参考-https://www.tutorialspoint.com/scala/scala_iterators.htm

2 个答案:

答案 0 :(得分:5)

  

我们怎么能[*]将Iterator用作Iterator("a", "number", "of", "words") [即使它不是Collection]?

此语法没有什么特别之处,可以使它Collections独占使用。我们在这里拥有的是apply上的object Iterator方法,该方法采用可变数量的参数(并返回由这些参数序列支持的Iterator实例):

/** Creates an iterator with given elements.
 *
 *  @param elems  The elements returned one-by-one from the iterator
 *  @return An iterator which produces the given elements on the
 *          first calls to `next`, and which has no further elements.
 */
 def apply[A](elems: A*): Iterator[A] = elems.iterator

您可以为自己的课堂做同样的事情。

这为“构建器方法”提供了一种不错的语法。

答案 1 :(得分:0)

迭代器是集合的粗略形式,或者是集合的接口。

查看Iterator随播对象上的apply方法,我们注意到它仅返回elems.iterator

/** Creates an iterator with given elements.
 *
 *  @param elems  The elements returned one-by-one from the iterator
 *  @return An iterator which produces the given elements on the
 *          first calls to `next`, and which has no further elements.
 */
 def apply[A](elems: A*): Iterator[A] = elems.iterator

elems这样的变量参数实际上是mutable.WrappedArray[A]类型,它实现了IterableLike特征,因此提供了Iterator [A]。