Колекціїї знаходяться в пакеті scala.collection та дочірніх пакетах mutable (змінюваний), immutable (незмінний), and generic (загальний).

Більшість колекцій мають три варіанти, які відрізняються мінливістю (mutability) і розташовані відповідно у пакетах scala.collection, scala.collection.immutable і scala.collection.mutable.

Колекції із scala.collection.immutable гарантовано незмінні, у scala.collection.mutable - змінні. Колекції пакету scala.collection містять базові реалізації, наприклад, collection.IndexedSeq [T] є суперкласом для <tt">collection.immutable.IndexedSeq [T]</tt> і collection.mutable.IndexedSeq [T].

За замовчуванням, Scala завжди вибирає незмінні колекцій. Щоб отримати змінювані версії необхідно написати або імпортувати явно клас із пакету collection.mutable.

Основні колекції

Traversable Iterable Seq IndexedSeq Vector ResizableArray GenericArray LinearSeq MutableList List Stream Buffer ListBuffer ArrayBuffer Set SortedSet TreeSet HashSet (mutable) LinkedHashSet HashSet (immutable) BitSet EmptySet, Set1, Set2, Set3, Set4 Map SortedMap TreeMap HashMap (mutable) LinkedHashMap (mutable) HashMap (immutable) EmptyMap, Map1, Map2, Map3, Map4

Traversable

Типаж (Trait) Traversable - вершина ієрархії класів Scala. Має єдину абстрактну операцію — foreach: def foreach[U](f: Elem => U)

Метод РезультатАбстрактний метод: xs foreach f Виконує функцію f для кожного елемента xsДодавання:xs ++ ys Колекція що складається з елементів xs і ys. ys є колекцією типу TraversableOnce, тобто Traversable або IteratorВідображення:xs map f Колекція одержана застосуванням функції f до кожного елемента xsxs flatMap f Колекція одержана застосуваням функції f, що повертає колекцію, до кожного елемента xs і конкатенацією результатівxs collect f Колекція одержана застосуваням часткової функції f до кожного елемента xs, на якому вона визначена і об'єднанням результатів Перетворення:xs.toArray Перетворює колекцію у масивxs.toList Перетворює колекцію у списокxs.toIterable Перетворює колекцію у iterablexs.toSeq Перетворює колекцію у послідовністьxs.toIndexedSeq Перетворює колекцію у індексовану послідовністьxs.toStream Перетворює колекцію у ліниво обчислюваний потікxs.toSet Перетворює колекцію у множинуxs.toMap Перетворює колекцію пар ключ/значення у відображення Копіювання:xs copyToBuffer buf копіює всі елементи колекції у буфер bufxs copyToArray(arr, s, len) Copies at most len arr starting at index s. The last two arguments are optionalSize info:xs.isEmpty Tests whether the collection is emptyxs.nonEmpty Tests whether the collection contains elementsxs.size The number of elements in the collectionxs.hasDefiniteSize True if xs is known to have finite sizeElement Retrieval:xs.head The first element of the collection (or, some element, if no order is defined)xs.headOption The first element of xs in an option value, or None if xs is emptyxs.last The last element of the collection (or, some element, if no order is defined)xs.lastOption The last element of xs in an option value, or None if xs is emptyxs find p An option containing the first element in xs that satisfies p, or None is no element qualifiesSubcollections:xs.tail The rest of the collection except xs.headxs.init The rest of the collection except xs.lastxs slice (from, to) A collection consisting of elements in some index range of xs (from from up to, and excluding to) xs take n A collection consisting of the first n elements of xs (or, some arbitrary n elements, if no order is defined)xs drop n The rest of the collection except xs take nxs takeWhile p The longest prefix of elements in the collection that all satisfy pxs dropWhile p The collection without the longest prefix of elements that all satisfy pxs filter p The collection consisting of those elements of xs that satisfy the predicate pxs withFilter p A non-strict filter of this collection. All operations on the resulting filter will only apply to those elements of xs for which the condition p is truexs filterNot p The collection consisting of those elements of xs that do not satisfy the predicate pSubdivisions:xs splitAt n Split xs at a position, giving the pair of collections (xs take n, xs drop n)xs span p Split xs according to a predicate, giving the pair of collections (xs takeWhile p, xs.dropWhile p) xs partition p Split xs into a pair of two collections; one with elements that satisfy the predicate p, the other with elements that do not, giving the pair of collections (xs filter p, xs.filterNot p)xs groupBy f Partition xs into a map of collections according to a discriminator function fElement Conditions:xs forall p A boolean indicating whether the predicate p holds for all elements of xsxs exists p A boolean indicating whether the predicate p holds for some element in xsxs count p The number of elements in xs that satisfy the predicate pFolds:(z /: xs)(op) Apply binary operation op between successive elements of xs, going left to right and starting with z(xs :\ z)(op) Apply binary operation op between successive elements of xs, going right to left and starting with zxs.foldLeft(z)(op) Same as (z /: xs)(op)xs.foldRight(z)(op) Same as (xs :\ z)(op)xs reduceLeft op Apply binary operation op between successive elements of non-empty collection xs, going left to rightxs reduceRight op Apply binary operation op between successive elements of non-empty collection xs, going right to leftSpecific Folds:xs.sum The sum of the numeric element values of collection xsxs.product The product of the numeric element values of collection xsxs.min The minimum of the ordered element values of collection xsxs.max The maximum of the ordered element values of collection xsStrings:xs addString (b, start, sep, end) Adds a string to StringBuilder b that shows all elements of xs between separators sep enclosed in strings start and end. start, sep, end are all optionalxs mkString (start, sep, end) Converts the collection to a string that shows all elements of xs between separators sep enclosed in strings start and end. start, sep, end are all optionalxs.stringPrefix The collection name at the beginning of the string returned from xs.toStringViews:xs.view Produces a view over xsxs view (from, to) Produces a view that represents the elements in some index range of xs

Iterable Має абстрактний метод — iterator, який повертає елементи колекції по одному.

foreach реалізований в Iterable через iterator.

def foreach[U](f: Elem => U): Unit = { val it = iterator while (it.hasNext) f(it.next()) }

Iterable наслідують Seq, Set, Map. Всі вони реалізують типаж PartialFunction з методами apply і isDefinedAt.

Для послідовностей Seq, apply - одержання елементу за індексом, починаючи з нуля. Наприклад, Seq(1, 2, 3)(0) == 1.

Для множин Set, apply - перевірка елемента на належність множині. Наприклад, Set('a', 'b', 'c')('a') == true, Set()('a') == false.

Для відображень Map, apply - вибір. Наприклад, Map('a' -> 1, 'b' -> 10, 'c' -> 100)('b') == 10.