scala.collection.immutable

class Stream

[source: scala/collection/immutable/Stream.scala]

abstract class Stream[+A]
extends LinearSeq[A] with GenericTraversableTemplate[A, Stream] with LinearSeqLike[A, Stream[A]]

The class Stream implements lazy lists where elements are only evaluated when they are needed. Here is an example:

 object Main extends Application {

   def from(n: Int): Stream[Int] =
     Stream.cons(n, from(n + 1))

   def sieve(s: Stream[Int]): Stream[Int] =
     Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 }))

   def primes = sieve(from(2))

   primes take 10 print
 }
 
Author
Martin Odersky, Matthias Zenger
Version
1.1 08/08/03
Since
2.8
Direct Known Subclasses:
Stream.Empty, Stream.Cons

Method Summary
override def ++ [B >: A, That](that : Traversable[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Create a new stream which contains all elements of this stream followed by all elements of Traversable `that'
override def ++ [B >: A, That](that : Iterator[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Create a new stream which contains all elements of this stream followed by all elements of Iterator `that'
override def addString (b : StringBuilder, start : java.lang.String, sep : java.lang.String, end : java.lang.String) : StringBuilder
Write all defined elements of this iterable into given string builder. The written text begins with the string start and is finished by the string end. Inside, the string representations of defined elements (w.r.t. the method toString()) are separated by the string sep. The method will not force evaluation of undefined elements. A tail of such elements will be represented by a "?" instead.
def append [B >: A](rest : => Traversable[B]) : Stream[B]
The stream resulting from the concatenation of this stream with the argument stream.
override def companion : GenericCompanion[Stream]
The factory companion object that builds instances of class CC
override def dropWhile (p : (A) => Boolean) : Stream[A]
Returns the longest suffix of this iterable whose first element does not satisfy the predicate p.
override final def filter (p : (A) => Boolean) : Stream[A]
Returns all the elements of this stream that satisfy the predicate p. The order of the elements is preserved.
override final def flatMap [B, That](f : (A) => Traversable[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Applies the given function f to each element of this stream, then concatenates the results.
override def flatten [B](implicit asTraversable : (A) => Traversable[B]) : Stream[B]
override final def foldLeft [B](z : B)(op : (B, A) => B) : B
Stream specialization of foldLeft which allows GC to collect along the way.
def force : Stream[A]
Force evaluation of the whole stream and return it
override final def foreach [B](f : (A) => B) : Unit
Apply the given function f to each element of this linear sequence (while respecting the order of the elements).
override def hasDefiniteSize : Boolean
Returns true if this collection is known to have finite size. This is the case if the collection type is strict, or if the collection type is non-strict (e.g. it's a Stream), but all collection elements have been computed. Many methods in this trait will not work on collections of infinite sizes.
abstract def head : A
The first element of this stream
override def init : Stream[A]
The stream without its last element.
abstract def isEmpty : Boolean
is this stream empty?
override final def map [B, That](f : (A) => B)(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Returns the stream resulting from applying the given function f to each element of this stream.
override def mkString (start : java.lang.String, sep : java.lang.String, end : java.lang.String) : java.lang.String
Returns a string representation of this traversable object. The resulting string begins with the string start and is finished by the string end. Inside, the string representations of elements (w.r.t. the method toString()) are separated by the string sep.
override def mkString : java.lang.String
Returns a string representation of this traversable object. The string representations of elements (w.r.t. the method toString()) follow each other without any separator string.
override def mkString (sep : java.lang.String) : java.lang.String
Returns a string representation of this traversable object. The string representations of elements (w.r.t. the method toString()) are separated by the string sep.
override def padTo [B >: A, That](len : Int, elem : B)(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Returns a new sequence of given length containing the elements of this sequence followed by zero or more occurrences of given elements.
override def partition (p : (A) => Boolean) : (Stream[A], Stream[A])
Returns all the elements of this stream that satisfy the predicate p. The order of the elements is preserved.
def print : Unit
Prints elements of this stream one by one, separated by commas
def print (sep : java.lang.String) : Unit
Prints elements of this stream one by one, separated by sep
override def removeDuplicates : Stream[A]
Builds a new stream from this stream in which any duplicates (wrt to ==) removed. Among duplicate elements, only the first one is retained in the result stream
override def reverse : Stream[A]
A list consisting of all elements of this list in reverse order.
override def slice (start : Int, end : Int) : Stream[A]
A substream starting at index `from` and extending up to (but not including) index `until`.
override def stringPrefix : java.lang.String
Defines the prefix of this object's toString representation as ``Stream''.
abstract def tail : Stream[A]
A stream consisting of the remaining elements of this stream after the first one.
protected abstract def tailDefined : Boolean
Is the tail of this stream defined?
override def take (n : Int) : Stream[A]
Returns the n first elements of this stream, or else the whole stream, if it has less than n elements.
override def takeRight (n : Int) : Stream[A]
Returns the rightmost n elements from this iterable.
override def takeWhile (p : (A) => Boolean) : Stream[A]
Returns the longest prefix of this stream whose elements satisfy the predicate p.
override def toStream : Stream[A]
Returns a stream with all elements in this iterable object.
override def toString : java.lang.String
Need to override string, so that it's not the Function1's string that gets mixed in.
override final def zip [A1 >: A, B, That](that : Iterable[B])(implicit bf : CanBuildFrom[Stream[A], (A1, B), That]) : That
Returns a stream formed from this stream and the specified stream that by associating each element of the former with the element at the same position in the latter. If one of the two streams is longer than the other, its remaining elements are ignored.
override def zipWithIndex [A1 >: A, That](implicit bf : CanBuildFrom[Stream[A], (A1, Int), That]) : That
Zips this iterable with its indices. `s.zipWithIndex` is equivalent to `s zip s.indices`
Methods inherited from LinearSeqLike
thisCollection, toCollection, length, apply, iterator, forall, exists, count, find, foldRight, reduceLeft, reduceRight, last, drop, dropRight, span, sameElements, lengthCompare, isDefinedAt, segmentLength, indexWhere, lastIndexWhere
Methods inherited from SeqLike
size, prefixLength, indexWhere, findIndexOf, indexOf, indexOf, lastIndexOf, lastIndexOf, lastIndexWhere, reverseMap, reverseIterator, reversedElements, startsWith, startsWith, endsWith, indexOfSeq, indexOfSeq, lastIndexOfSeq, lastIndexOfSeq, contains, union, diff, intersect, patch, updated, +:, :+, sortWith, sortWith, sortBy, toSeq, indices, view, view, hashCode, equals, findLastIndexOf, equalsWith, containsSlice, projection
Methods inherited from PartialFunction
orElse, andThen
Methods inherited from Function1
compose
Methods inherited from IterableLike
elements, toIterable, copyToArray, zipAll, canEqual, first, firstOption
Methods inherited from GenericTraversableTemplate
newBuilder, genericBuilder, unzip, transpose
Methods inherited from TraversableLike
repr, nonEmpty, filterNot, partialMap, remove, groupBy, /:, :\, reduceLeftOption, reduceRightOption, sum, product, min, max, headOption, lastOption, splitAt, copyToBuffer, copyToArray, toArray, toList, toIndexedSeq, toSet, addString, addString, withFilter
Methods inherited from AnyRef
getClass, clone, notify, notifyAll, wait, wait, wait, finalize, ==, !=, eq, ne, synchronized
Methods inherited from Any
==, !=, isInstanceOf, asInstanceOf
Method Details
override def companion : GenericCompanion[Stream]
The factory companion object that builds instances of class CC
Overrides
LinearSeq.companion, GenericTraversableTemplate.companion

abstract def isEmpty : Boolean
is this stream empty?
Overrides
GenericTraversableTemplate.isEmpty, LinearSeqLike.isEmpty

abstract def head : A
The first element of this stream
Throws
Predef.NoSuchElementException - if the stream is empty.
Overrides
GenericTraversableTemplate.head, LinearSeqLike.head

abstract def tail : Stream[A]
A stream consisting of the remaining elements of this stream after the first one.
Throws
Predef.UnsupportedOperationException - if the stream is empty.
Overrides
LinearSeqLike.tail

protected abstract def tailDefined : Boolean
Is the tail of this stream defined?

def append[B >: A](rest : => Traversable[B]) : Stream[B]
The stream resulting from the concatenation of this stream with the argument stream.
Parameters
rest - The stream that gets appended to this stream

def force : Stream[A]
Force evaluation of the whole stream and return it

def print : Unit
Prints elements of this stream one by one, separated by commas

def print(sep : java.lang.String) : Unit
Prints elements of this stream one by one, separated by sep
Parameters
sep - The separator string printed between consecutive elements.

override def toStream : Stream[A]
Returns a stream with all elements in this iterable object.

override def hasDefiniteSize : Boolean
Returns true if this collection is known to have finite size. This is the case if the collection type is strict, or if the collection type is non-strict (e.g. it's a Stream), but all collection elements have been computed. Many methods in this trait will not work on collections of infinite sizes.

override def ++[B >: A, That](that : Traversable[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Create a new stream which contains all elements of this stream followed by all elements of Traversable `that'
Notes
It's subtle why this works. We know that if the target type of the Builder That is either a Stream, or one of its supertypes, or undefined, then StreamBuilder will be chosen for the implicit. we recognize that fact and optimize to get more laziness.

override def ++[B >: A, That](that : Iterator[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Create a new stream which contains all elements of this stream followed by all elements of Iterator `that'

override final def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Returns the stream resulting from applying the given function f to each element of this stream.
Parameters
f - function to apply to each element.
Returns
f(a0), ..., f(an) if this sequence is a0, ..., an.

override final def flatMap[B, That](f : (A) => Traversable[B])(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Applies the given function f to each element of this stream, then concatenates the results.
Parameters
f - the function to apply on each element.
Returns
f(a0) ::: ... ::: f(an) if this stream is [a0, ..., an].

override final def filter(p : (A) => Boolean) : Stream[A]
Returns all the elements of this stream that satisfy the predicate p. The order of the elements is preserved.
Parameters
p - the predicate used to filter the stream.
Returns
the elements of this stream satisfying p.

@tailrec

override final def foreach[B](f : (A) => B) : Unit
Apply the given function f to each element of this linear sequence (while respecting the order of the elements).
Parameters
f - the treatment to apply to each element.
Notes
Overridden here as final to trigger tail-call optimization, which replaces 'this' with 'tail' at each iteration. This is absolutely necessary for allowing the GC to collect the underlying stream as elements are consumed.
Overrides
GenericTraversableTemplate.foreach, LinearSeqLike.foreach

@tailrec

override final def foldLeft[B](z : B)(op : (B, A) => B) : B
Stream specialization of foldLeft which allows GC to collect along the way.
Overrides
LinearSeqLike.foldLeft

override def partition(p : (A) => Boolean) : (Stream[A], Stream[A])
Returns all the elements of this stream that satisfy the predicate p. The order of the elements is preserved.
Parameters
p - the predicate used to filter the stream.
Returns
the elements of this stream satisfying p.

override final def zip[A1 >: A, B, That](that : Iterable[B])(implicit bf : CanBuildFrom[Stream[A], (A1, B), That]) : That
Returns a stream formed from this stream and the specified stream that by associating each element of the former with the element at the same position in the latter. If one of the two streams is longer than the other, its remaining elements are ignored.
Returns
Stream({a0,b0}, ..., {amin(m,n),bmin(m,n))} when Stream(a0, ..., am) zip Stream(b0, ..., bn) is invoked.

override def zipWithIndex[A1 >: A, That](implicit bf : CanBuildFrom[Stream[A], (A1, Int), That]) : That
Zips this iterable with its indices. `s.zipWithIndex` is equivalent to `s zip s.indices`

override def addString(b : StringBuilder, start : java.lang.String, sep : java.lang.String, end : java.lang.String) : StringBuilder
Write all defined elements of this iterable into given string builder. The written text begins with the string start and is finished by the string end. Inside, the string representations of defined elements (w.r.t. the method toString()) are separated by the string sep. The method will not force evaluation of undefined elements. A tail of such elements will be represented by a "?" instead.

override def mkString(start : java.lang.String, sep : java.lang.String, end : java.lang.String) : java.lang.String
Returns a string representation of this traversable object. The resulting string begins with the string start and is finished by the string end. Inside, the string representations of elements (w.r.t. the method toString()) are separated by the string sep.
Examples
List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"
Parameters
start - starting string.
sep - separator string.
end - ending string.
Returns
a string representation of this traversable object.

override def mkString(sep : java.lang.String) : java.lang.String
Returns a string representation of this traversable object. The string representations of elements (w.r.t. the method toString()) are separated by the string sep.
Parameters
sep - separator string.
Returns
a string representation of this traversable object.

override def mkString : java.lang.String
Returns a string representation of this traversable object. The string representations of elements (w.r.t. the method toString()) follow each other without any separator string.

override def toString : java.lang.String
Need to override string, so that it's not the Function1's string that gets mixed in.

override def take(n : Int) : Stream[A]
Returns the n first elements of this stream, or else the whole stream, if it has less than n elements.
Parameters
n - the number of elements to take.
Returns
the n first elements of this stream.
Overrides
LinearSeqLike.take

override def slice(start : Int, end : Int) : Stream[A]
A substream starting at index `from` and extending up to (but not including) index `until`.
Notes
This is equivalent to (but possibly more efficient than) c.drop(from).take(to - from)
Might return different results for different runs, unless this iterable is ordered
Parameters
start - The index of the first element of the returned subsequence
end - The index of the element following the returned subsequence
Throws
IndexOutOfBoundsException - if from < 0 or length < from + len
Overrides
LinearSeqLike.slice

override def init : Stream[A]
The stream without its last element.
Throws
Predef.UnsupportedOperationException - if the stream is empty.

override def takeRight(n : Int) : Stream[A]
Returns the rightmost n elements from this iterable.
Parameters
n - the number of elements to take

override def takeWhile(p : (A) => Boolean) : Stream[A]
Returns the longest prefix of this stream whose elements satisfy the predicate p.
Parameters
p - the test predicate.
Overrides
LinearSeqLike.takeWhile

override def dropWhile(p : (A) => Boolean) : Stream[A]
Returns the longest suffix of this iterable whose first element does not satisfy the predicate p.
Parameters
p - the test predicate.

override def removeDuplicates : Stream[A]
Builds a new stream from this stream in which any duplicates (wrt to ==) removed. Among duplicate elements, only the first one is retained in the result stream

override def padTo[B >: A, That](len : Int, elem : B)(implicit bf : CanBuildFrom[Stream[A], B, That]) : That
Returns a new sequence of given length containing the elements of this sequence followed by zero or more occurrences of given elements.

override def reverse : Stream[A]
A list consisting of all elements of this list in reverse order.

override def flatten[B](implicit asTraversable : (A) => Traversable[B]) : Stream[B]
Overrides
GenericTraversableTemplate.flatten

override def stringPrefix : java.lang.String
Defines the prefix of this object's toString representation as ``Stream''.