Scala Collection
Scala provides a good set of collection implementations and abstractions of several collection types.
Scala collections are divided into mutable and immutable collections.
Mutable collections can be updated or expanded 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 each of these operations returns a new collection in every case, leaving the original collection unchanged.
Next, we will introduce the use of several commonly used collection types:
| No. | Collections and Descriptions |
|---|---|
| 1 | Scala List
The characteristic of a List is that its elements are stored linearly, and the collection can contain duplicate objects. Reference API Documentation |
| 2 | Scala Set
Set is the simplest kind of collection. The objects in a Set are not sorted in any particular way, and there are no duplicate objects. Reference API Documentation |
| 3 | Scala Map
A 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. Reference API Documentation |
| 4 | Scala Tuples
A tuple is a collection of values of different types |
| 5 | Scala Option
Option[T] represents a container that may or may not contain a value. |
| 6 | Scala Iterator
An iterator is not a container; more precisely, it is a way to access the elements of a container one by one. |
Example
The following code snippet demonstrates definitions 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
,
"Runoob"
)
// define an Option
val
x
:
Option
[
Int
]
=
Some
(
5
)