Scala Collection

Scala provides a great set of collection implementations, offering abstractions of some collection types.

Scala collections are divided into mutable and immutable collections.

Mutable collections can be updated or extended in place. This means you can modify, add, or remove elements of a collection.

Immutable collection classes, by contrast, never change. However, you can still simulate add, remove, or update operations. But these operations will return a new collection in each case, while leaving the original collection unchanged.

Next, we will introduce the applications of several commonly used collection types:

Serial number Collection and description
1 Scala List

The feature of List is that its elements are stored in a linear fashion, and duplicate objects can be stored in the collection.

ReferenceAPI documentation

2 Scala Set

Set is the simplest type of collection. Objects in the collection are not sorted in any particular way, and there are no duplicate objects.

ReferenceAPI documentation

3 Scala Map

Map is a collection that maps key objects to value objects. Each of its elements contains a pair of a key object and a value object.

ReferenceAPI documentation

4 Scala Tuple

A tuple is a collection of values of different types.

5 Scala Option

Option[T] represents a container that may contain a value, or may not contain a value.

6 Scala Iterator

An iterator is not a container, but more precisely a method to access the elements in a container one by one.

Examples

The following code demonstrates the definition examples of all the above collection types:

// Define an integer List
val x = List(1,2,3,4)

// Define a Set
val x = Set(1,3,5,7)

// Define a Map
val x = Map("one" -> 1, "two" -> 2, "three" -> 3)

// Create a tuple with two elements of different types
val x = (10, "Example")

// Define an Option
val x:Option[Int] = Some(5)
Other extensions