trait Iterable {
type Iterator
def iterator(): Iterator
}
trait Iterator {
type Element
def next(): Option[Element]
}
class Range(start: Int, stop: Int) extends Iterable {
override type Iterator = RangeIterator
override def iterator(): Iterator =
new RangeIterator(start, stop)
}
class RangeIterator(var start: Int, stop: Int) extends Iterator {
override type Element = Int
override def next(): Option[Int] =
if (start >= stop) {
None
} else {
val value = start
start += 1
Some(value)
}
}
object Main {
def main(args: Array[String]): Unit = {
val range = new Range(1, 10);
{
val iterator = range.iterator()
println(iterator.next())
println(iterator.next())
println(iterator.next())
}
{
val iterator = range.iterator()
println(iterator.next())
println(iterator.next())
println(iterator.next())
}
}
}