Range Over Iterators in Scala
Our first program will demonstrate how to use iterators. Here’s the full source code.
Let’s break down what’s happening in this code:
List Class:
- We define a generic
List
class with a nested Element
class representing each node in the linked list. - The
push
method adds elements to the end of the list. - The
all
method returns an iterator for the list.
Iterator for List:
- The
all
method creates a new iterator that traverses the list starting from the head, yielding each element’s value until the end.
Generating Fibonacci Numbers:
- The
genFib
method creates an iterator for Fibonacci numbers. It keeps generating values as long as needed.
Main Method:
- We create a list and add some integers.
- We use a
for
loop with the list’s iterator to print each element. - We collect all elements into a vector and print them.
- We use another iterator to generate Fibonacci numbers and print them until we encounter a number greater than or equal to 10.
To run the program, compile and execute it using the following commands:
This will output:
Now that we can create and use iterators in Scala, let’s learn more about the language’s capabilities.