package collection
Contains the base traits and objects needed to use and extend Scala's collection library.
Guide
A detailed guide for using the collections library is available at http://docs.scala-lang.org/overviews/collections/introduction.html. Developers looking to extend the collections library can find a description of its architecture at http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html.
Using Collections
It is convenient to treat all collections as either a scala.collection.Traversable or scala.collection.Iterable, as these traits define the vast majority of operations on a collection.
Collections can, of course, be treated as specifically as needed, and the library is designed to ensure that the methods that transform collections will return a collection of the same type:
scala> val array = Array(1,2,3,4,5,6) array: Array[Int] = Array(1, 2, 3, 4, 5, 6) scala> array map { _.toString } res0: Array[String] = Array(1, 2, 3, 4, 5, 6) scala> val list = List(1,2,3,4,5,6) list: List[Int] = List(1, 2, 3, 4, 5, 6) scala> list map { _.toString } res1: List[String] = List(1, 2, 3, 4, 5, 6)
Creating Collections
The most common way to create a collection is to use its companion object as
a factory. The three most commonly used collections are
scala.collection.Seq, scala.collection.immutable.Set, and
scala.collection.immutable.Map.
They can be used directly as shown below since their companion objects are
all available as type aliases in either the scala package or in
scala.Predef. New collections are created like this:
scala> val seq = Seq(1,2,3,4,1) seq: Seq[Int] = List(1, 2, 3, 4, 1) scala> val set = Set(1,2,3,4,1) set: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4) scala> val map = Map(1 -> "one", 2 -> "two", 3 -> "three", 2 -> "too") map: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> too, 3 -> three)
It is also typical to prefer the scala.collection.immutable collections
over those in scala.collection.mutable; the types aliased in
the scala.Predef object are the immutable versions.
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 concrete parallel collections also have specific performance characteristics which are described in the parallel collections guide
Converting to and from Java Collections
The scala.collection.JavaConverters object provides a collection
of decorators that allow converting between Scala and Java collections using asScala
and asJava methods.
- Source
- package.scala
- Alphabetic
- By Inheritance
- collection
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
-
abstract
class
AbstractIterable[+A] extends AbstractTraversable[A] with Iterable[A]
Explicit instantiation of the
Iterabletrait to reduce class file size in subclasses. -
abstract
class
AbstractIterator[+A] extends Iterator[A]
Explicit instantiation of the
Iteratortrait to reduce class file size in subclasses. -
abstract
class
AbstractMap[K, +V] extends AbstractIterable[(K, V)] with Map[K, V]
Explicit instantiation of the
Maptrait to reduce class file size in subclasses. -
abstract
class
AbstractSeq[+A] extends AbstractIterable[A] with Seq[A]
Explicit instantiation of the
Seqtrait to reduce class file size in subclasses. -
abstract
class
AbstractSet[A] extends AbstractIterable[A] with Set[A]
Explicit instantiation of the
Settrait to reduce class file size in subclasses. -
abstract
class
AbstractTraversable[+A] extends Traversable[A]
Explicit instantiation of the
Traversabletrait to reduce class file size in subclasses. -
trait
BitSet extends SortedSet[Int] with BitSetLike[BitSet]
A common base class for mutable and immutable bitsets.
A common base class for mutable and immutable bitsets.
Bitsets are sets of non-negative integers which are represented as variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is determined by the largest number stored in it.
-
trait
BitSetLike[+This <: BitSetLike[This] with SortedSet[Int]] extends SortedSetLike[Int, This]
A template trait for bitsets.
A template trait for bitsets.
Bitsets are sets of non-negative integers which are represented as variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is determined by the largest number stored in it.
This trait provides most of the operations of a
BitSetindependently of its representation. It is inherited by all concrete implementations of bitsets.- This
the type of the bitset itself.
-
trait
BufferedIterator[+A] extends Iterator[A]
Buffered iterators are iterators which provide a method
headthat inspects the next element without discarding it.Buffered iterators are iterators which provide a method
headthat inspects the next element without discarding it.- Since
2.8
- trait CustomParallelizable[+A, +ParRepr <: Parallel] extends Parallelizable[A, ParRepr]
-
trait
DefaultMap[A, +B] extends Map[A, B]
A default map which implements the
+and-methods of maps.A default map which implements the
+and-methods of maps.Instances that inherit from
DefaultMap[A, B]still have to define:def get(key: A): Option[B] def iterator: Iterator[(A, B)]
It refers back to the original map.
It might also be advisable to override
foreachorsizeif efficient implementations can be found.- Since
2.8
-
trait
GenIterable[+A] extends GenIterableLike[A, GenIterable[A]] with GenTraversable[A] with GenericTraversableTemplate[A, GenIterable]
A trait for all iterable collections which may possibly have their operations implemented in parallel.
A trait for all iterable collections which may possibly have their operations implemented in parallel.
- Since
2.9
-
trait
GenIterableLike[+A, +Repr] extends GenTraversableLike[A, Repr]
A template trait for all iterable collections which may possibly have their operations implemented in parallel.
A template trait for all iterable collections which may possibly have their operations implemented in parallel.
This trait contains abstract methods and methods that can be implemented directly in terms of other methods.
-
trait
GenMap[K, +V] extends GenMapLike[K, V, GenMap[K, V]] with GenIterable[(K, V)]
A trait for all traversable collections which may possibly have their operations implemented in parallel.
A trait for all traversable collections which may possibly have their operations implemented in parallel.
- Since
2.9
-
trait
GenMapLike[K, +V, +Repr] extends GenIterableLike[(K, V), Repr] with Equals with Parallelizable[(K, V), ParMap[K, V]]
A trait for all maps upon which operations may be implemented in parallel.
-
trait
GenSeq[+A] extends GenSeqLike[A, GenSeq[A]] with GenIterable[A] with Equals with GenericTraversableTemplate[A, GenSeq]
A trait for all sequences which may possibly have their operations implemented in parallel.
A trait for all sequences which may possibly have their operations implemented in parallel.
- Since
2.9
-
trait
GenSeqLike[+A, +Repr] extends GenIterableLike[A, Repr] with Equals with Parallelizable[A, ParSeq[A]]
A template trait for all sequences which may be traversed in parallel.
-
trait
GenSet[A] extends GenSetLike[A, GenSet[A]] with GenIterable[A] with GenericSetTemplate[A, GenSet]
A trait for sets which may possibly have their operations implemented in parallel.
A trait for sets which may possibly have their operations implemented in parallel.
- Since
2.9
-
trait
GenSetLike[A, +Repr] extends GenIterableLike[A, Repr] with (A) ⇒ Boolean with Equals with Parallelizable[A, ParSet[A]]
A template trait for sets which may possibly have their operations implemented in parallel.
-
trait
GenTraversable[+A] extends GenTraversableLike[A, GenTraversable[A]] with GenTraversableOnce[A] with GenericTraversableTemplate[A, GenTraversable]
A trait for all traversable collections which may possibly have their operations implemented in parallel.
A trait for all traversable collections which may possibly have their operations implemented in parallel.
- Since
2.9
-
trait
GenTraversableLike[+A, +Repr] extends GenTraversableOnce[A] with Parallelizable[A, ParIterable[A]]
A template trait for all traversable collections upon which operations may be implemented in parallel.
-
trait
GenTraversableOnce[+A] extends Any
A template trait for all traversable-once objects which may be traversed in parallel.
A template trait for all traversable-once objects which may be traversed in parallel.
Methods in this trait are either abstract or can be implemented in terms of other methods.
-
trait
IndexedSeq[+A] extends Seq[A] with GenericTraversableTemplate[A, IndexedSeq] with IndexedSeqLike[A, IndexedSeq[A]]
A base trait for indexed sequences.
A base trait for indexed sequences.
Indexed sequences support constant-time or near constant-time element access and length computation. They are defined in terms of abstract methods
applyfor indexing andlength.Indexed sequences do not add any new methods to
Seq, but promise efficient implementations of random access patterns. -
trait
IndexedSeqLike[+A, +Repr] extends SeqLike[A, Repr]
A template trait for indexed sequences of type
IndexedSeq[A].A template trait for indexed sequences of type
IndexedSeq[A].Indexed sequences support constant-time or near constant-time element access and length computation. They are defined in terms of abstract methods
applyfor indexing andlength.Indexed sequences do not add any new methods to
Seq, but promise efficient implementations of random access patterns.This trait just implements
iteratorin terms ofapplyandlength. However, seeIndexedSeqOptimizedfor an implementation trait that overrides operations to make them run faster under the assumption of fast random access withapply. -
trait
IndexedSeqOptimized[+A, +Repr] extends IndexedSeqLike[A, Repr]
A template trait for indexed sequences of type
IndexedSeq[A]which optimizes the implementation of several methods under the assumption of fast random access.A template trait for indexed sequences of type
IndexedSeq[A]which optimizes the implementation of several methods under the assumption of fast random access.Indexed sequences support constant-time or near constant-time element access and length computation. They are defined in terms of abstract methods
applyfor indexing andlength.Indexed sequences do not add any new methods to
Seq, but promise efficient implementations of random access patterns. -
trait
Iterable[+A] extends Traversable[A] with GenIterable[A] with GenericTraversableTemplate[A, Iterable] with IterableLike[A, Iterable[A]]
A base trait for iterable collections.
A base trait for iterable collections.
This is a base trait for all Scala collections that define an
iteratormethod to step through one-by-one the collection's elements. Implementations of this trait need to provide a concrete method with signature:def iterator: Iterator[A]They also need to provide a method
newBuilderwhich creates a builder for collections of the same kind.This trait implements
Iterable'sforeachmethod by stepping through all elements usingiterator. Subclasses should re-implementforeachwith something more efficient, if possible.This trait adds methods
iterator,sameElements,takeRight,dropRightto the methods inherited from trait `Traversable`.Note: This trait replaces every method that uses
breakinTraversableLikeby an iterator version. -
trait
IterableLike[+A, +Repr] extends Equals with TraversableLike[A, Repr] with GenIterableLike[A, Repr]
A template trait for iterable collections of type
Iterable[A].A template trait for iterable collections of type
Iterable[A].This is a base trait for all Scala collections that define an
iteratormethod to step through one-by-one the collection's elements. Implementations of this trait need to provide a concrete method with signature:def iterator: Iterator[A]They also need to provide a method
newBuilderwhich creates a builder for collections of the same kind.This trait implements
Iterable'sforeachmethod by stepping through all elements usingiterator. Subclasses should re-implementforeachwith something more efficient, if possible.This trait adds methods
iterator,sameElements,takeRight,dropRightto the methods inherited from trait `Traversable`.Note: This trait replaces every method that uses
breakinTraversableLikeby an iterator version. -
trait
IterableView[+A, +Coll] extends IterableViewLike[A, Coll, IterableView[A, Coll]]
A base trait for non-strict views of
Iterables.A base trait for non-strict views of
Iterables.A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view. All views for iterable collections are defined by re-interpreting theiteratormethod. -
trait
IterableViewLike[+A, +Coll, +This <: IterableView[A, Coll] with IterableViewLike[A, Coll, This]] extends Iterable[A] with IterableLike[A, This] with TraversableView[A, Coll] with TraversableViewLike[A, Coll, This]
A template trait for non-strict views of iterable collections.
A template trait for non-strict views of iterable collections.
A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view. All views for iterable collections are defined by re-interpreting theiteratormethod. -
trait
Iterator[+A] extends TraversableOnce[A]
Iterators are data structures that allow to iterate over a sequence of elements.
Iterators are data structures that allow to iterate over a sequence of elements. They have a
hasNextmethod for checking if there is a next element available, and anextmethod which returns the next element and advances the iterator.An iterator is mutable: most operations on it change its state. While it is often used to iterate through the elements of a collection, it can also be used without being backed by any collection (see constructors on the companion object).
It is of particular importance to note that, unless stated otherwise, one should never use an iterator after calling a method on it. The two most important exceptions are also the sole abstract methods:
nextandhasNext.Both these methods can be called any number of times without having to discard the iterator. Note that even
hasNextmay cause mutation -- such as when iterating from an input stream, where it will block until the stream is closed or some input becomes available.Consider this example for safe and unsafe use:
def f[A](it: Iterator[A]) = { if (it.hasNext) { // Safe to reuse "it" after "hasNext" it.next // Safe to reuse "it" after "next" val remainder = it.drop(2) // it is *not* safe to use "it" again after this line! remainder.take(2) // it is *not* safe to use "remainder" after this line! } else it }
- Since
1
-
trait
LinearSeq[+A] extends Seq[A] with GenericTraversableTemplate[A, LinearSeq] with LinearSeqLike[A, LinearSeq[A]]
A base trait for linear sequences.
A base trait for linear sequences.
Linear sequences have reasonably efficient
head,tail, andisEmptymethods. If these methods provide the fastest way to traverse the collection, a collectionCollthat extends this trait should also extendLinearSeqOptimized[A, Coll[A]]. -
trait
LinearSeqLike[+A, +Repr <: LinearSeqLike[A, Repr]] extends SeqLike[A, Repr]
A template trait for linear sequences of type
LinearSeq[A].A template trait for linear sequences of type
LinearSeq[A].This trait just implements
iteratorandcorrespondsin terms ofisEmpty,head, andtail. However, seeLinearSeqOptimizedfor an implementation trait that overrides many more operations to make them run faster under the assumption of fast linear access withheadandtail.Linear sequences do not add any new methods to
Seq, but promise efficient implementations of linear access patterns.- A
the element type of the sequence
- Repr
the type of the actual sequence containing the elements.
- Since
2.8
-
trait
LinearSeqOptimized[+A, +Repr <: LinearSeqOptimized[A, Repr]] extends LinearSeqLike[A, Repr]
A template trait for linear sequences of type
LinearSeq[A]which optimizes the implementation of various methods under the assumption of fast linear access.A template trait for linear sequences of type
LinearSeq[A]which optimizes the implementation of various methods under the assumption of fast linear access.Linear-optimized sequences implement most operations in in terms of three methods, which are assumed to have efficient implementations. These are:
def isEmpty: Boolean def head: A def tail: Repr
Here,
Ais the type of the sequence elements andRepris the type of the sequence itself. Note that default implementations are provided via inheritance, but these should be overridden for performance. -
trait
Map[K, +V] extends Iterable[(K, V)] with GenMap[K, V] with MapLike[K, V, Map[K, V]]
A map from keys of type
Kto values of typeV.A map from keys of type
Kto values of typeV.Implementation note: This trait provides most of the operations of a
Mapindependently of its representation. It is typically inherited by concrete implementations of maps.To implement a concrete map, you need to provide implementations of the following methods:
def get(key: K): Option[V] def iterator: Iterator[(K, V)] def + [V1 >: V](kv: (K, V1)): This def -(key: K): This
If you wish that methods like
take,drop,filteralso return the same kind of map you should also override:def empty: ThisIt is also good idea to override methods
foreachandsizefor efficiency.Note: If you do not have specific implementations for
addand-in mind, you might consider inheriting fromDefaultMapinstead.Note: If your additions and mutations return the same kind of map as the map you are defining, you should inherit from
MapLikeas well.- K
the type of the keys in this map.
- V
the type of the values associated with keys.
- Since
1.0
-
trait
MapLike[K, +V, +This <: MapLike[K, V, This] with Map[K, V]] extends PartialFunction[K, V] with IterableLike[(K, V), This] with GenMapLike[K, V, This] with Subtractable[K, This] with Parallelizable[(K, V), ParMap[K, V]]
A template trait for maps, which associate keys with values.
A template trait for maps, which associate keys with values.
Implementation note: This trait provides most of the operations of a
Mapindependently of its representation. It is typically inherited by concrete implementations of maps.To implement a concrete map, you need to provide implementations of the following methods:
def get(key: K): Option[V] def iterator: Iterator[(K, V)] def + [V1 >: V](kv: (K, V1)): This def -(key: K): This
If you wish that methods like
take,drop,filteralso return the same kind of map you should also override:def empty: ThisIt is also good idea to override methods
foreachandsizefor efficiency.- Since
2.8
-
trait
Parallel extends AnyRef
A marker trait for collections which have their operations parallelised.
A marker trait for collections which have their operations parallelised.
- Since
2.9
-
trait
Parallelizable[+A, +ParRepr <: Parallel] extends Any
This trait describes collections which can be turned into parallel collections by invoking the method
par.This trait describes collections which can be turned into parallel collections by invoking the method
par. Parallelizable collections may be parameterized with a target type different than their own.- A
the type of the elements in the collection
- ParRepr
the actual type of the collection, which has to be parallel
-
trait
Seq[+A] extends PartialFunction[Int, A] with Iterable[A] with GenSeq[A] with GenericTraversableTemplate[A, Seq] with SeqLike[A, Seq[A]]
A base trait for sequences.
A base trait for sequences.
Sequences are special cases of iterable collections of class
Iterable. Unlike iterables, sequences always have a defined order of elements. Sequences provide a methodapplyfor indexing. Indices range from0up to thelengthof a sequence. Sequences support a number of methods to find occurrences of elements or subsequences, includingsegmentLength,prefixLength,indexWhere,indexOf,lastIndexWhere,lastIndexOf,startsWith,endsWith,indexOfSlice.Another way to see a sequence is as a
PartialFunctionfromIntvalues to the element type of the sequence. TheisDefinedAtmethod of a sequence returnstruefor the interval from0untillength.Sequences can be accessed in reverse order of their elements, using methods
reverseandreverseIterator.Sequences have two principal subtraits,
IndexedSeqandLinearSeq, which give different guarantees for performance. AnIndexedSeqprovides fast random-access of elements and a fastlengthoperation. ALinearSeqprovides fast access only to the first element viahead, but also has a fasttailoperation. -
trait
SeqLike[+A, +Repr] extends IterableLike[A, Repr] with GenSeqLike[A, Repr] with Parallelizable[A, ParSeq[A]]
A template trait for sequences of type
Seq[A]A template trait for sequences of type
Seq[A]Sequences are special cases of iterable collections of class
Iterable. Unlike iterables, sequences always have a defined order of elements. Sequences provide a methodapplyfor indexing. Indices range from0up to thelengthof a sequence. Sequences support a number of methods to find occurrences of elements or subsequences, includingsegmentLength,prefixLength,indexWhere,indexOf,lastIndexWhere,lastIndexOf,startsWith,endsWith,indexOfSlice.Another way to see a sequence is as a
PartialFunctionfromIntvalues to the element type of the sequence. TheisDefinedAtmethod of a sequence returnstruefor the interval from0untillength.Sequences can be accessed in reverse order of their elements, using methods
reverseandreverseIterator.Sequences have two principal subtraits,
IndexedSeqandLinearSeq, which give different guarantees for performance. AnIndexedSeqprovides fast random-access of elements and a fastlengthoperation. ALinearSeqprovides fast access only to the first element viahead, but also has a fasttailoperation. -
trait
SeqView[+A, +Coll] extends SeqViewLike[A, Coll, SeqView[A, Coll]]
A base trait for non-strict views of sequences.
A base trait for non-strict views of sequences.
A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view. All views for sequences are defined by re-interpreting thelengthandapplymethods. -
trait
SeqViewLike[+A, +Coll, +This <: SeqView[A, Coll] with SeqViewLike[A, Coll, This]] extends Seq[A] with SeqLike[A, This] with IterableView[A, Coll] with IterableViewLike[A, Coll, This]
A template trait for non-strict views of sequences.
A template trait for non-strict views of sequences.
A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view. All views for sequences are defined by re-interpreting thelengthandapplymethods. -
trait
Set[A] extends (A) ⇒ Boolean with Iterable[A] with GenSet[A] with GenericSetTemplate[A, Set] with SetLike[A, Set[A]]
A base trait for all sets, mutable as well as immutable.
A base trait for all sets, mutable as well as immutable.
A set is a collection that contains no duplicate elements.
To implement a concrete set, you need to provide implementations of the following methods:
def contains(key: A): Boolean def iterator: Iterator[A] def +(elem: A): This def -(elem: A): This
If you wish that methods like
take,drop,filterreturn the same kind of set, you should also override:def empty: ThisIt is also good idea to override methods
foreachandsizefor efficiency.Implementation note: If your additions and mutations return the same kind of set as the set you are defining, you should inherit from
SetLikeas well.- Since
1.0
-
trait
SetLike[A, +This <: SetLike[A, This] with Set[A]] extends IterableLike[A, This] with GenSetLike[A, This] with Subtractable[A, This] with Parallelizable[A, ParSet[A]]
A template trait for sets.
A template trait for sets.
A set is a collection that contains no duplicate elements.
To implement a concrete set, you need to provide implementations of the following methods:
def contains(key: A): Boolean def iterator: Iterator[A] def +(elem: A): This def -(elem: A): This
If you wish that methods like
take,drop,filterreturn the same kind of set, you should also override:def empty: ThisIt is also good idea to override methods
foreachandsizefor efficiency.Implementation note: This trait provides most of the operations of a
Setindependently of its representation. It is typically inherited by concrete implementations of sets.- Since
2.8
-
trait
SortedMap[A, +B] extends Map[A, B] with SortedMapLike[A, B, SortedMap[A, B]]
A map whose keys are sorted.
A map whose keys are sorted.
- Since
2.4
-
trait
SortedMapLike[A, +B, +This <: SortedMapLike[A, B, This] with SortedMap[A, B]] extends Sorted[A, This] with MapLike[A, B, This]
A template for maps whose keys are sorted.
A template for maps whose keys are sorted. To create a concrete sorted map, you need to implement the rangeImpl method, in addition to those of
MapLike.- Since
2.8
-
trait
SortedSet[A] extends Set[A] with SortedSetLike[A, SortedSet[A]]
A sorted set.
A sorted set.
- Since
2.4
-
trait
SortedSetLike[A, +This <: SortedSet[A] with SortedSetLike[A, This]] extends Sorted[A, This] with SetLike[A, This]
A template for sets which are sorted.
A template for sets which are sorted.
- Since
2.8
-
trait
Traversable[+A] extends TraversableLike[A, Traversable[A]] with GenTraversable[A] with TraversableOnce[A] with GenericTraversableTemplate[A, Traversable]
A trait for traversable collections.
A trait for traversable collections. All operations are guaranteed to be performed in a single-threaded manner.
This is a base trait of all kinds of Scala collections. It implements the behavior common to all collections, in terms of a method
foreachwith signature:def foreach[U](f: Elem => U): Unit
Collection classes mixing in this trait provide a concrete
foreachmethod which traverses all the elements contained in the collection, applying a given function to each. They also need to provide a methodnewBuilderwhich creates a builder for collections of the same kind.A traversable class might or might not have two properties: strictness and orderedness. Neither is represented as a type.
The instances of a strict collection class have all their elements computed before they can be used as values. By contrast, instances of a non-strict collection class may defer computation of some of their elements until after the instance is available as a value. A typical example of a non-strict collection class is a scala.collection.immutable.Stream. A more general class of examples are
TraversableViews.If a collection is an instance of an ordered collection class, traversing its elements with
foreachwill always visit elements in the same order, even for different runs of the program. If the class is not ordered,foreachcan visit elements in different orders for different runs (but it will keep the same order in the same run).'A typical example of a collection class which is not ordered is a
HashMapof objects. The traversal order for hash maps will depend on the hash codes of its elements, and these hash codes might differ from one run to the next. By contrast, aLinkedHashMapis ordered because itsforeachmethod visits elements in the order they were inserted into theHashMap. -
trait
TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with FilterMonadic[A, Repr] with TraversableOnce[A] with GenTraversableLike[A, Repr] with Parallelizable[A, ParIterable[A]]
A template trait for traversable collections of type
Traversable[A].A template trait for traversable collections of type
Traversable[A].This is a base trait of all kinds of Scala collections. It implements the behavior common to all collections, in terms of a method
foreachwith signature:def foreach[U](f: Elem => U): Unit
Collection classes mixing in this trait provide a concrete
foreachmethod which traverses all the elements contained in the collection, applying a given function to each. They also need to provide a methodnewBuilderwhich creates a builder for collections of the same kind.A traversable class might or might not have two properties: strictness and orderedness. Neither is represented as a type.
The instances of a strict collection class have all their elements computed before they can be used as values. By contrast, instances of a non-strict collection class may defer computation of some of their elements until after the instance is available as a value. A typical example of a non-strict collection class is a scala.collection.immutable.Stream. A more general class of examples are
TraversableViews.If a collection is an instance of an ordered collection class, traversing its elements with
foreachwill always visit elements in the same order, even for different runs of the program. If the class is not ordered,foreachcan visit elements in different orders for different runs (but it will keep the same order in the same run).'A typical example of a collection class which is not ordered is a
HashMapof objects. The traversal order for hash maps will depend on the hash codes of its elements, and these hash codes might differ from one run to the next. By contrast, aLinkedHashMapis ordered because itsforeachmethod visits elements in the order they were inserted into theHashMap. -
trait
TraversableOnce[+A] extends GenTraversableOnce[A]
A template trait for collections which can be traversed either once only or one or more times.
A template trait for collections which can be traversed either once only or one or more times.
This trait exists primarily to eliminate code duplication between
IteratorandTraversable, and thus implements some of the common methods that can be implemented solely in terms of foreach without access to aBuilder. It also includes a number of abstract methods whose implementations are provided byIterator,Traversable, etc. It contains implementations common toIteratorsandTraversables, such as folds, conversions, and other operations which traverse some or all of the elements and return a derived value. Directly subclassingTraversableOnceis not recommended - instead, consider declaring anIteratorwith anextandhasNextmethod or creating anIteratorwith one of the methods on theIteratorobject. Consider declaring a subclass ofTraversableinstead if the elements can be traversed repeatedly.- Since
2.8
-
trait
TraversableView[+A, +Coll] extends TraversableViewLike[A, Coll, TraversableView[A, Coll]]
A base trait for non-strict views of traversable collections.
A base trait for non-strict views of traversable collections.
A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view.All views for traversable collections are defined by creating a new
foreachmethod. -
trait
TraversableViewLike[+A, +Coll, +This <: TraversableView[A, Coll] with TraversableViewLike[A, Coll, This]] extends Traversable[A] with TraversableLike[A, This] with ViewMkString[A]
A template trait for non-strict views of traversable collections.
A template trait for non-strict views of traversable collections.
A view is a lazy version of some collection. Collection transformers such as
maporfilteror++do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied. The collection elements are accessed, and the view operations are applied, when a non-view result is needed, or when theforcemethod is called on a view.All views for traversable collections are defined by creating a new
foreachmethod.Implementation note: Methods such as
maporflatMapon this view will not invoke the implicitly passedBuilderfactory, but will return a new view directly, to preserve by-name behavior. The new view is then cast to the factory's result type. This means that everyCanBuildFromthat takes aViewas itsFromtype parameter must yield the same view (or a generic superclass of it) as its result parameter. If that assumption is broken, cast errors might result. - trait ViewMkString[+A] extends AnyRef
-
trait
IterableProxy[+A] extends Iterable[A] with IterableProxyLike[A, Iterable[A]]
This trait implements a proxy for iterable objects.
This trait implements a proxy for iterable objects. It forwards all calls to a different iterable object.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.3) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
IterableProxyLike[+A, +Repr <: IterableLike[A, Repr] with Iterable[A]] extends IterableLike[A, Repr] with TraversableProxyLike[A, Repr]
This trait implements a proxy for Iterable objects.
This trait implements a proxy for Iterable objects. It forwards all calls to a different Iterable object.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
MapProxy[A, +B] extends Map[A, B] with MapProxyLike[A, B, Map[A, B]]
This is a simple wrapper class for scala.collection.Map.
This is a simple wrapper class for scala.collection.Map. It is most useful for assembling customized map abstractions dynamically using object composition and forwarding.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.3) proxying is deprecated due to lack of use and compiler-level support
- Since
1
-
trait
MapProxyLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]] extends MapLike[A, B, This] with IterableProxyLike[(A, B), This]
This trait implements a proxy for Map objects.
This trait implements a proxy for Map objects. It forwards all calls to a different Map object.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
SeqProxy[+A] extends Seq[A] with SeqProxyLike[A, Seq[A]]
This trait implements a proxy for sequence objects.
This trait implements a proxy for sequence objects. It forwards all calls to a different sequence object.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
SeqProxyLike[+A, +Repr <: SeqLike[A, Repr] with Seq[A]] extends SeqLike[A, Repr] with IterableProxyLike[A, Repr]
This trait implements a proxy for sequences.
This trait implements a proxy for sequences. It forwards all calls to a different sequence.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
SetProxy[A] extends Set[A] with SetProxyLike[A, Set[A]]
This is a simple wrapper class for scala.collection.Set.
This is a simple wrapper class for scala.collection.Set. It is most useful for assembling customized set abstractions dynamically using object composition and forwarding.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.3) proxying is deprecated due to lack of use and compiler-level support
- Since
2.0
-
trait
SetProxyLike[A, +This <: SetLike[A, This] with Set[A]] extends SetLike[A, This] with IterableProxyLike[A, This]
This trait implements a proxy for sets.
This trait implements a proxy for sets. It forwards all calls to a different set.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
TraversableProxy[+A] extends Traversable[A] with TraversableProxyLike[A, Traversable[A]]
This trait implements a proxy for traversable objects.
This trait implements a proxy for traversable objects. It forwards all calls to a different traversable object
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.3) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
-
trait
TraversableProxyLike[+A, +Repr <: TraversableLike[A, Repr] with Traversable[A]] extends TraversableLike[A, Repr] with Proxy
This trait implements a proxy for Traversable objects.
This trait implements a proxy for Traversable objects. It forwards all calls to a different Traversable object.
- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) proxying is deprecated due to lack of use and compiler-level support
- Since
2.8
Value Members
-
def
breakOut[From, T, To](implicit b: CanBuildFrom[Nothing, T, To]): CanBuildFrom[From, T, To]
Provides a CanBuildFrom instance that builds a specific target collection (
To') irrespective of the original collection (From'). -
object
+:
An extractor used to head/tail deconstruct sequences.
-
object
:+
An extractor used to init/last deconstruct sequences.
-
object
BitSet extends BitSetFactory[BitSet]
This object provides a set of operations to create
values.BitSet -
object
BitSetLike
Companion object for BitSets.
Companion object for BitSets. Contains private data only
- object GenIterable extends GenTraversableFactory[GenIterable]
- object GenMap extends GenMapFactory[GenMap]
- object GenSeq extends GenTraversableFactory[GenSeq]
- object GenSet extends GenTraversableFactory[GenSet]
- object GenTraversable extends GenTraversableFactory[GenTraversable]
-
object
IndexedSeq extends IndexedSeqFactory[IndexedSeq]
This object provides a set of operations to create
values.IndexedSeqThis object provides a set of operations to create
values. The current default implementation of aIndexedSeqIndexedSeqis aVector. -
object
Iterable extends GenTraversableFactory[Iterable] with TraversableFactory[Iterable]
This object provides a set of operations to create
values.IterableThis object provides a set of operations to create
values. The current default implementation of aIterableIterableis aList. -
object
IterableView
An object containing the necessary implicit definitions to make
IterableViews work.An object containing the necessary implicit definitions to make
IterableViews work. Its definitions are generally not accessed directly by clients. -
object
Iterator
The
Iteratorobject provides various functions for creating specialized iterators.The
Iteratorobject provides various functions for creating specialized iterators.- Since
2.8
-
object
JavaConverters extends DecorateAsJava with DecorateAsScala
A variety of decorators that enable converting between Scala and Java collections using extension methods,
asScalaandasJava.A variety of decorators that enable converting between Scala and Java collections using extension methods,
asScalaandasJava.The extension methods return adapters for the corresponding API.
The following conversions are supported via
asScalaandasJava:scala.collection.Iterable <=> java.lang.Iterable scala.collection.Iterator <=> java.util.Iterator scala.collection.mutable.Buffer <=> java.util.List scala.collection.mutable.Set <=> java.util.Set scala.collection.mutable.Map <=> java.util.Map scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap
The following conversions are supported via
asScalaand through specially-named extension methods to convert to Java collections, as shown:scala.collection.Iterable <=> java.util.Collection (via asJavaCollection) scala.collection.Iterator <=> java.util.Enumeration (via asJavaEnumeration) scala.collection.mutable.Map <=> java.util.Dictionary (via asJavaDictionary)
In addition, the following one-way conversions are provided via
asJava:scala.collection.Seq => java.util.List scala.collection.mutable.Seq => java.util.List scala.collection.Set => java.util.Set scala.collection.Map => java.util.Map
The following one way conversion is provided via
asScala:java.util.Properties => scala.collection.mutable.Map
In all cases, converting from a source type to a target type and back again will return the original source object. For example:
import scala.collection.JavaConverters._ val source = new scala.collection.mutable.ListBuffer[Int] val target: java.util.List[Int] = source.asJava val other: scala.collection.mutable.Buffer[Int] = target.asScala assert(source eq other)
Alternatively, the conversion methods have descriptive names and can be invoked explicitly.
scala> val vs = java.util.Arrays.asList("hi", "bye") vs: java.util.List[String] = [hi, bye] scala> val ss = asScalaIterator(vs.iterator) ss: Iterator[String] = non-empty iterator scala> .toList res0: List[String] = List(hi, bye) scala> val ss = asScalaBuffer(vs) ss: scala.collection.mutable.Buffer[String] = Buffer(hi, bye)
- Since
2.8.1
-
object
LinearSeq extends SeqFactory[LinearSeq]
This object provides a set of operations to create
values.LinearSeqThis object provides a set of operations to create
values. The current default implementation of aLinearSeqLinearSeqis aList. -
object
Map extends MapFactory[Map]
This object provides a set of operations needed to create
values.Map -
object
Searching
A collection of wrappers that provide sequence classes with search functionality.
A collection of wrappers that provide sequence classes with search functionality.
Example usage:
import scala.collection.Searching._ val l = List(1, 2, 3, 4, 5) l.search(3) // == Found(2)
-
object
Seq extends SeqFactory[Seq]
This object provides a set of operations to create
values.SeqThis object provides a set of operations to create
values. The current default implementation of aSeqSeqis aList. -
object
SeqLike
The companion object for trait
SeqLike. -
object
SeqView
An object containing the necessary implicit definitions to make
SeqViews work.An object containing the necessary implicit definitions to make
SeqViews work. Its definitions are generally not accessed directly by clients. -
object
Set extends SetFactory[Set]
This object provides a set of operations needed to create
values.SetThis object provides a set of operations needed to create
values. The current default implementation of aSetSetis one ofEmptySet,Set1,Set2,Set3,Set4in classimmutable.Setfor sets of sizes up to 4, and aimmutable.HashSetfor sets of larger sizes. -
object
SortedMap extends SortedMapFactory[SortedMap]
- Since
2.8
-
object
SortedSet extends SortedSetFactory[SortedSet]
- Since
2.8
-
object
Traversable extends GenTraversableFactory[Traversable] with TraversableFactory[Traversable]
This object provides a set of operations to create
Traversablevalues.This object provides a set of operations to create
Traversablevalues. The current default implementation of a Traversable is aList. - object TraversableOnce
-
object
TraversableView
An object containing the necessary implicit definitions to make
TraversableViews work.An object containing the necessary implicit definitions to make
TraversableViews work. Its definitions are generally not accessed directly by clients.
Deprecated Value Members
-
object
JavaConversions extends WrapAsScala with WrapAsJava
A variety of implicit conversions supporting interoperability between Scala and Java collections.
A variety of implicit conversions supporting interoperability between Scala and Java collections.
The following conversions are supported:
scala.collection.Iterable <=> java.lang.Iterable scala.collection.Iterable <=> java.util.Collection scala.collection.Iterator <=> java.util.{ Iterator, Enumeration } scala.collection.mutable.Buffer <=> java.util.List scala.collection.mutable.Set <=> java.util.Set scala.collection.mutable.Map <=> java.util.{ Map, Dictionary } scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap
In all cases, converting from a source type to a target type and back again will return the original source object:
import scala.collection.JavaConversions._ val sl = new scala.collection.mutable.ListBuffer[Int] val jl : java.util.List[Int] = sl val sl2 : scala.collection.mutable.Buffer[Int] = jl assert(sl eq sl2)
In addition, the following one way conversions are provided:
scala.collection.Seq => java.util.List scala.collection.mutable.Seq => java.util.List scala.collection.Set => java.util.Set scala.collection.Map => java.util.Map java.util.Properties => scala.collection.mutable.Map[String, String]
The transparent conversions provided here are considered fragile because they can result in unexpected behavior and performance.
Therefore, this API has been deprecated and
JavaConvertersshould be used instead.JavaConvertersprovides the same conversions, but through extension methods.- Annotations
- @deprecated
- Deprecated
(Since version 2.12.0) use JavaConverters
- Since
2.8
This is the documentation for the Scala standard library.
Package structure
The scala package contains core types like
Int,Float,ArrayorOptionwhich are accessible in all Scala compilation units without explicit qualification or imports.Notable packages include:
scala.collectionand its sub-packages contain Scala's collections frameworkscala.collection.immutable- Immutable, sequential data-structures such asVector,List,Range,HashMaporHashSetscala.collection.mutable- Mutable, sequential data-structures such asArrayBuffer,StringBuilder,HashMaporHashSetscala.collection.concurrent- Mutable, concurrent data-structures such asTrieMapscala.collection.parallel.immutable- Immutable, parallel data-structures such asParVector,ParRange,ParHashMaporParHashSetscala.collection.parallel.mutable- Mutable, parallel data-structures such asParArray,ParHashMap,ParTrieMaporParHashSetscala.concurrent- Primitives for concurrent programming such asFuturesandPromisesscala.io- Input and output operationsscala.math- Basic math functions and additional numeric types likeBigIntandBigDecimalscala.sys- Interaction with other processes and the operating systemscala.util.matching- Regular expressionsOther packages exist. See the complete list on the right.
Additional parts of the standard library are shipped as separate libraries. These include:
scala.reflect- Scala's reflection API (scala-reflect.jar)scala.xml- XML parsing, manipulation, and serialization (scala-xml.jar)scala.swing- A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)scala.util.parsing- Parser combinators (scala-parser-combinators.jar)Automatic imports
Identifiers in the scala package and the
scala.Predefobject are always in scope by default.Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example,
Listis an alias forscala.collection.immutable.List.Other aliases refer to classes provided by the underlying platform. For example, on the JVM,
Stringis an alias forjava.lang.String.