「Chapter 13 Iterators」の編集履歴(バックアップ)一覧に戻る
Iterators are the imperative version of streams. Like streams, iterators describe potentially infinite lists. However, there is no data-structure which contains the elements of an iterator. Instead, iterators allow one to step through the sequence, using two abstract methods next and hasNext.
イテレーターは、ストリームの手続き版です。ストリームのように、イテレーターには無限リストを記述する能力があります。しかし、イテレーターの要素を含むデータ構造はありません。代わりに、二つの抽象メソッドnextとhasNextを使うことで、イテレーターは列を通しての処理が可能です。
trait Iterator[+A] { def hasNext: Boolean def next: A
Method next returns successive elements. Method hasNext indicates whether there are still more elements to be returned by next. Iterators also support some other methods, which are explained later.
メソッドnextは、連続的な列の要素を返します。メソッドhasNextはnextで返すべき要素がまだあるかどうかを示します。イテレーターは他にもいくつかのメソッドをサポートしていますが、それは後ほど説明します。
As an example, here is an application which prints the squares of all numbers from 1 to 100.
例として1から100までの数の平方を表示してみます。
val it: Iterator[Int] = Iterator.range(1, 100) while (it.hasNext) { val x = it.next println(x * x) }