Also note that the collections library was carefully designed to include several implementations of
each of the three basic collection types. These implementations have specific performance
characteristics which are described
in the guide.

The Stream class also employs memoization such that previously computed
values are converted from Stream elements to concrete values of type A.
To illustrate, we will alter body of the fibs value above and take some
more values:

The definition of fibs is a val not a method. The memoization of the
Stream requires us to have somewhere to store the information and a val
allows us to do that.

While the Stream is actually being modified during access, this does not
change the notion of its immutability. Once the values are memoized they do
not change and values that have yet to be memoized still "exist", they
simply haven't been realized yet.

One must be cautious of memoization; you can very quickly eat up large
amounts of memory if you're not careful. The reason for this is that the
memoization of the Stream creates a structure much like
scala.collection.immutable.List. So long as something is holding on to
the head, the head holds on to the tail, and so it continues recursively.
If, on the other hand, there is nothing holding on to the head (e.g. we used
def to define the Stream) then once it is no longer being used directly,
it disappears.

Note that some operations, including drop, dropWhile,
flatMap or collect may process a large number of intermediate
elements before returning. These necessarily hold onto the head, since
they are methods on Stream, and a stream holds its own head. For
computations of this sort where memoization is not desired, use
Iterator when possible.

// For example, let's build the natural numbers and do some silly iteration// over them.// We'll start with a silly iterationdef loop(s: String, i: Int, iter: Iterator[Int]): Unit = {
// Stop after 200,000if (i < 200001) {
if (i % 50000 == 0) println(s + i)
loop(s, iter.next, iter)
}
}
// Our first Stream definition will be a val definitionval stream1: Stream[Int] = {
def loop(v: Int): Stream[Int] = v #:: loop(v + 1)
loop(0)
}
// Because stream1 is a val, everything that the iterator produces is held// by virtue of the fact that the head of the Stream is held in stream1val it1 = stream1.iterator
loop("Iterator1: ", it1.next, it1)
// We can redefine this Stream such that all we have is the Iterator left// and allow the Stream to be garbage collected as required. Using a def// to provide the Stream ensures that no val is holding onto the head as// is the case with stream1def stream2: Stream[Int] = {
def loop(v: Int): Stream[Int] = v #:: loop(v + 1)
loop(0)
}
val it2 = stream2.iterator
loop("Iterator2: ", it2.next, it2)
// And, of course, we don't actually need a Stream at all for such a simple// problem. There's no reason to use a Stream if you don't actually need// one.val it3 = new Iterator[Int] {
var i = -1def hasNext = truedef next(): Int = { i += 1; i }
}
loop("Iterator3: ", it3.next, it3)

The fact that tail works at all is of interest. In the definition of
fibs we have an initial (0, 1, Stream(...)) so tail is deterministic.
If we defined fibs such that only 0 were concretely known then the act
of determining tail would require the evaluation of tail which would
cause an infinite recursion and stack overflow. If we define a definition
where the tail is not initially computable then we're going to have an
infinite recursion:

// The first time we try to access the tail we're going to need more// information which will require us to recurse, which will require us to// recurse, which...lazyval sov: Stream[Vector[Int]] = Vector(0) #:: sov.zip(sov.tail).map { n => n._1 ++ n._2 }

The definition of fibs above creates a larger number of objects than
necessary depending on how you might want to implement it. The following
implementation provides a more "cost effective" implementation due to the
fact that it has a more direct route to the numbers themselves:

Note that mkString forces evaluation of a Stream, but addString does
not. In both cases, a Stream that is or ends in a cycle
(e.g. lazy val s: Stream[Int] = 0 #:: s) will convert additional trips
through the cycle to .... Additionally, addString will display an
un-memoized tail as ?.

Equivalent to x.hashCode except for boxed numeric types and null.
For numerics, it returns a hash value which is consistent
with value equality: if two value type instances compare
as true, then ## will produce the same hash value for each
of them.
For null returns a hashcode where null.hashCode throws a
NullPointerException.

Create a new stream which contains all elements of this stream followed by
all elements of Traversable that.

Create a new stream which contains all elements of this stream followed by
all elements of Traversable that.

B

The element type of the returned collection.That

That

the class of the returned collection. Where possible, That is
the same class as the current collection class Repr, but this
depends on the element type B being admissible for that class,
which means that an implicit instance of type CanBuildFrom[Repr, B, That]
is found.

It's subtle why this works. We know that if the target type of the
scala.collection.mutable.BuilderThat 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.

,

This method doesn't cause the Stream to be fully realized but it
should be noted that using the ++ operator from another collection type
could cause infinite realization of a Stream. For example, referring to
the definition of fibs in the preamble, the following would never return:
List(BigInt(12)) ++ fibs.

This overload exists because: for the implementation of ++: we should
reuse that of ++ because many collections override it with more
efficient versions.

Since TraversableOnce has no ++ method, we have to implement that
directly, but Traversable and down can use the overload.

B

the element type of the returned collection.

That

the class of the returned collection. Where possible, That is
the same class as the current collection class Repr, but this
depends on the element type B being admissible for that class,
which means that an implicit instance of type CanBuildFrom[Repr, B, That]
is found.

that

the traversable to append.

bf

an implicit value of class CanBuildFrom which determines
the result class That from the current representation type Repr and
the new element type B.

returns

a new collection of type That which contains all elements
of this traversable collection followed by all elements of that.

Write all defined elements of this iterable into given string builder.

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. A cyclic stream is represented by a "..."
at the point where the cycle repeats.

Appends all elements of this traversable or iterator to a string builder.

Appends all elements of this traversable or iterator to a string builder.
The written text consists of the string representations (w.r.t. the method
toString) of all elements of this traversable or iterator without any separator string.

Appends all elements of this traversable or iterator to a string builder using a separator string.

Appends all elements of this traversable or iterator to a string builder using a separator string.
The written text consists of the string representations (w.r.t. the method toString)
of all elements of this traversable or iterator, separated by the string sep.

Aggregates the results of applying an operator to subsequent elements.

Aggregates the results of applying an operator to subsequent elements.

This is a more general form of fold and reduce. It is similar to
foldLeft in that it doesn't require the result to be a supertype of the
element type. In addition, it allows parallel collections to be processed
in chunks, and then combines the intermediate results.

aggregate splits the traversable or iterator into partitions and processes each
partition by sequentially applying seqop, starting with z (like
foldLeft). Those intermediate results are then combined by using
combop (like fold). The implementation of this operation may operate
on an arbitrary number of collection partitions (even 1), so combop may
be invoked an arbitrary number of times (even 0).

As an example, consider summing up the integer values of a list of chars.
The initial value for the sum is 0. First, seqop transforms each input
character to an Int and adds it to the sum (of the partition). Then,
combop just needs to sum up the intermediate results of the partitions:

the initial value for the accumulated result of the partition - this
will typically be the neutral element for the seqop operator (e.g.
Nil for list concatenation or 0 for summation) and may be evaluated
more than once

seqop

an operator used to accumulate results within a partition

combop

an associative operator used to combine results from different partitions

Applies this partial function to the given argument when it is contained in the function domain.

Applies this partial function to the given argument when it is contained in the function domain.
Applies fallback function where this partial function is not defined.

Note that expression pf.applyOrElse(x, default) is equivalent to

if(pf isDefinedAt x) pf(x) else default(x)

except that applyOrElse method can be implemented more efficiently.
For all partial function literals the compiler generates an applyOrElse implementation which
avoids double evaluation of pattern matchers and guards.
This makes applyOrElse the basis for the efficient implementation for many operations and scenarios, such as:

combining partial functions into orElse/andThen chains does not lead to
excessive apply/isDefinedAt evaluation

lift and unlift do not evaluate source functions twice on each invocation

For non-literal partial function classes with nontrivial isDefinedAt method
it is recommended to override applyOrElse with custom implementation that avoids
double isDefinedAt evaluation. This may result in better performance
and more predictable behavior w.r.t. side effects.

Note that the success of a cast at runtime is modulo Scala's erasure semantics.
Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at
runtime, while the expression List(1).asInstanceOf[List[String]] will not.
In the latter example, because the type argument is erased as part of compilation it is
not possible to check whether the contents of the list are of the requested type.

Iterates over combinations. A _combination_ of length n is a subsequence of
the original sequence, with the elements taken in order. Thus, "xy" and "yy"
are both length-2 combinations of "xyy", but "yx" is not. If there is
more than one way to generate the same subsequence, only one will be returned.

For example, "xyyy" has three different ways to generate "xy" depending on
whether the first, second, or third "y" is selected. However, since all are
identical, only one will be chosen. Which of the three will be taken is an
implementation detail that is not defined.

returns

An Iterator which traverses the possible n-element combinations of this sequence.

Copies the elements of this stream to an array.
Fills the given array xs with at most len elements of
this stream, starting at position start.
Copying will stop once either the end of the current stream is reached,
or the end of the target array is reached, or len elements have been copied.

Copies the elements of this stream to an array.
Fills the given array xs with values of this stream.
Copying will stop once either the end of the current stream is reached,
or the end of the target array is reached.

Copies the elements of this stream to an array.
Fills the given array xs with values of this stream, beginning at index start.
Copying will stop once either the end of the current stream is reached,
or the end of the target array is reached.

[use case] Computes the multiset difference between this stream and another sequence.

[use case]

Computes the multiset difference between this stream and another sequence.

Note: will not terminate for infinite-sized collections.

that

the sequence of elements to remove

returns

a new stream which contains all elements of this stream
except some of occurrences of elements that also appear in that.
If an element value x appears
n times in that, then the first n occurrences of x will not form
part of the result, but any following occurrences will.

Tests whether the argument (that) is a reference to the receiver object (this).

Tests whether the argument (that) is a reference to the receiver object (this).

The eq method implements an equivalence relation on
non-null instances of AnyRef, and has three additional properties:

It is consistent: for any non-null instances x and y of type AnyRef, multiple invocations of
x.eq(y) consistently returns true or consistently returns false.

For any non-null instance x of type AnyRef, x.eq(null) and null.eq(x) returns false.

null.eq(null) returns true.

When overriding the equals or hashCode methods, it is important to ensure that their behavior is
consistent with reference equality. Therefore, if two objects are references to each other (o1 eq o2), they
should be equal to each other (o1 == o2) and they should hash to the same value (o1.hashCode == o2.hashCode).

returns

true if the argument is a reference to the receiver object; false otherwise.

Applies the given function f to each element of this stream, then
concatenates the results.

Applies the given function f to each element of this stream, then
concatenates the results. As with map this function does not need to
realize the entire Stream but continues to keep it as a lazy Stream.

B

The element type of the returned collection That.

That

the class of the returned collection. Where possible, That is
the same class as the current collection class Repr, but this
depends on the element type B being admissible for that class,
which means that an implicit instance of type CanBuildFrom[Repr, B, That]
is found.

f

the function to apply on each element.

bf

an implicit value of class CanBuildFrom which determines the
result class That from the current representation type Repr
and the new element type B.

Folds the elements of this traversable or iterator using the specified associative
binary operator.

Folds the elements of this traversable or iterator using the specified associative
binary operator.

The order in which operations are performed on elements is unspecified
and may be nondeterministic.

Note: will not terminate for infinite-sized collections.

A1

a type parameter for the binary operator, a supertype of A.

z

a neutral element for the fold operation; may be added to the result
an arbitrary number of times, and must not change the result (e.g., Nil for list concatenation,
0 for addition, or 1 for multiplication).

op

a binary operator that must be associative.

returns

the result of applying the fold operator op between all the elements and z, or z if this traversable or iterator is empty.

Often we use Streams to represent an infinite set or series. If
that's the case for your particular Stream then this function will never
return and will probably crash the VM with an OutOfMemory exception.
This function will not hang on a finite cycle, however.

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.

,

This function will force the realization of the entire stream
unless the f throws an exception.

Tests whether this stream is known to have a finite size.
All strict collections are known to have finite size. For a non-strict
collection such as Stream, the predicate returns true if all
elements have been computed. It returns false if the stream is
not yet evaluated to the end. Non-empty Iterators usually return
false even if they were created from a collection with a known
finite size.

Note: many collection methods will not work on collections of infinite sizes.
The typical failure mode is an infinite loop. These methods always attempt a
traversal without checking first that hasDefiniteSize returns true.
However, checking hasDefiniteSize can provide an assurance that size is
well-defined and non-termination is not a concern.

returns

true if this collection is known to have finite size,
false otherwise.

Iterates over the inits of this traversable collection. The first value will be this
traversable collection and the final one will be an empty traversable collection, with the intervening
values the results of successive applications of init.

[use case] Computes the multiset intersection between this stream and another sequence.

[use case]

Computes the multiset intersection between this stream and another sequence.

Note: may not terminate for infinite-sized collections.

that

the sequence of elements to intersect with.

returns

a new stream which contains all elements of this stream
which also appear in that.
If an element value x appears
n times in that, then the first n occurrences of x will be retained
in the result, but any following occurrences will be omitted.

Note that the result of the test is modulo Scala's erasure semantics.
Therefore the expression 1.isInstanceOf[String] will return false, while the
expression List(1).isInstanceOf[List[String]] will return true.
In the latter example, because the type argument is erased as part of compilation it is
not possible to check whether the contents of the list are of the specified type.

returns

true if the receiver object is an instance of erasure of type T0; false otherwise.

Returns the stream resulting from applying the given function f to each
element of this stream.

Returns the stream resulting from applying the given function f to each
element of this stream. This returns a lazy Stream such that it does not
need to be fully realized.

B

The element type of the returned collection That.

That

the class of the returned collection. Where possible, That is
the same class as the current collection class Repr, but this
depends on the element type B being admissible for that class,
which means that an implicit instance of type CanBuildFrom[Repr, B, That]
is found.

f

function to apply to each element.

bf

an implicit value of class CanBuildFrom which determines the
result class That from the current representation type Repr
and the new element type B.

Displays all elements of this stream in a string using start, end, and
separator strings.

Displays all elements of this stream in a string using start, end, and
separator strings.

start

the starting string.

sep

the separator string.

end

the ending string.

returns

a string representation of this stream. The resulting string
begins with the string start and ends with the string
end. Inside, the string representations (w.r.t. the method
toString) of all elements of this stream are separated by
the string sep.

Composes this partial function with a fallback partial function which
gets applied where this partial function is not defined.

Composes this partial function with a fallback partial function which
gets applied where this partial function is not defined.

A1

the argument type of the fallback function

B1

the result type of the fallback function

that

the fallback function

returns

a partial function which has as domain the union of the domains
of this partial function and that. The resulting partial function
takes x to this(x) where this is defined, and to that(x) where it is not.

For most collection types, this method creates a new parallel collection by copying
all the elements. For these collection, par takes linear time. Mutable collections
in this category do not produce a mutable parallel collection that has the same
underlying dataset, so changes in one collection will not be reflected in the other one.

Specific collections (e.g. ParArray or mutable.ParHashMap) override this default
behaviour by creating a parallel collection which shares the same underlying dataset.
For these collections, par takes constant or sublinear time.

the product of all elements in this stream of numbers of type Int.
Instead of Int, any other type T with an implicit Numeric[T] implementation
can be used as element type of the stream and as result type of product.
Examples of such types are: Long, Float, Double, BigInt.

the sum of all elements in this stream of numbers of type Int.
Instead of Int, any other type T with an implicit Numeric[T] implementation
can be used as element type of the stream and as result type of sum.
Examples of such types are: Long, Float, Double, BigInt.

Converts this stream to a map. This method is unavailable unless
the elements are members of Tuple2, each ((T, U)) becoming a key-value
pair in the map. Duplicate keys will be overwritten by later keys:
if this is an unordered collection, which key is in the resulting map
is undefined.

Note: will not terminate for infinite-sized collections.

returns

a map of type immutable.Map[T, U]
containing all key/value pairs of type (T, U) of this stream.

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.

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.

The return type of this function may not be obvious. The lazy aspect of
the returned value is different than that of partition. In partition
we get back a scala.Tuple2 of two lazy Streams whereas here we get
back a single lazy Stream of scala.Tuple2s where the
scala.Tuple2's type signature is (A1, B).

A1

The type of the first parameter of the zipped tuple

B

The type of the second parameter of the zipped tuple

That

The type of the returned Stream.

that

The iterable providing the second half of each result pair

bf

an implicit value of class CanBuildFrom which determines the
result class That from the current representation type Repr
and the new element type (A1, B).

[use case] Returns a stream formed from this stream and another iterable collection
by combining corresponding elements in pairs.

[use case]

Returns a stream formed from this stream and another iterable collection
by combining corresponding elements in pairs.
If one of the two collections is shorter than the other,
placeholder elements are used to extend the shorter collection to the length of the longer.

B

the type of the second half of the returned pairs

that

The iterable providing the second half of each result pair

thisElem

the element to be used to fill up the result if this stream is shorter than that.

thatElem

the element to be used to fill up the result if that is shorter than this stream.

returns

a new stream containing pairs consisting of
corresponding elements of this stream and that. The length
of the returned collection is the maximum of the lengths of this stream and that.
If this stream is shorter than that, thisElem values are used to pad the result.
If that is shorter than this stream, thatElem values are used to pad the result.