Easy Tutorial
❮ Scala Closures Scala Intro ❯

Scala Collection

Scala offers a robust set of collection implementations, providing abstractions for various collection types.

Scala collections are divided into mutable and immutable collections.

Mutable collections can be updated or extended where appropriate. This means you can modify, add, or remove elements from a collection.

In contrast, immutable collection classes will never change. However, you can still simulate operations for adding, removing, or updating. But these operations will return a new collection in every case while leaving the original collection unchanged.

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

Number Collection and Description
1 Scala List (List) The characteristic of a List is that its elements are stored linearly, and duplicate objects can be stored in the collection. Refer to the API documentation
2 Scala Set (Set) Set is the simplest type of collection. The objects in a set are not ordered in a specific way, and there are no duplicate objects. Refer to the API documentation
3 Scala Map (Map) Map is a collection that maps key objects to value objects, with each element containing a pair of key and value objects. Refer to the API documentation
4 Scala Tuples Tuples are collections 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 (Iterator) An iterator is not a container, but more accurately a method for accessing the elements of a container one by one.

Examples

The following code determines and 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 elements of different types
val x = (10, "tutorialpro")

// Define an Option
val x:Option[Int] = Some(5)
❮ Scala Closures Scala Intro ❯