There are several types of collections in Scala.
Iterable()
creates an empty collection.
List()
creates an empty list.
Vector(20,130)
, creates a vector with two elements 20
and 130
in it.
List(20,130)
, creates a list with two elements 20
and 130
in it.
Iterator(1, 2, 3)
, an iterator containing three numbers.
Set(Apples, oranges)
creates a set of two fruits.
Hashset(Apples, oranges)
creates a hashset of two fruits.
Map('apple' -> 23 , 'banana' -> 45)
creates a map of key-value pairs to map from characters to integers.
In Scala, a programmer can easily create a collection by defining a collection name and initializing the values of a collection in parentheses. For examples,
Map('apple' -> 23 , 'banana' -> 45)
creates a map with some key value pairs.
Now let’s see how does it work. When you write List(23,45)
, a function, List.apply(23, 45)
is called. This apply()
method is a companion object of the Class List. The function apply
takes some arguments and creates a list of the passed argument. The companion object is then applied to all the collections: lists, lazylists, Vectors, Seq, Set, Map, Iterables, etc.
Apart from
.apply()
, all collections also have another companion object,.empty
, to create an empty collection.
The companion objects provide several methods in a collection such as concat
(to join two collections together, fill
(for generating collections of a given dimension: single dimension, multi-dimension, etc.), range
(create a range of numbers).
Free Resources