How to create collections from scratch in Scala

Collections in Scala

There are several types of collections in Scala.

  1. Iterable() creates an empty collection.

  2. List() creates an empty list.

  3. Vector(20,130), creates a vector with two elements 20 and 130 in it.

  4. List(20,130), creates a list with two elements 20 and 130 in it.

  5. Iterator(1, 2, 3), an iterator containing three numbers.

  6. Set(Apples, oranges) creates a set of two fruits.

  7. Hashset(Apples, oranges) creates a hashset of two fruits.

  8. 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.

Collections in Scala
Collections in Scala

Collection creation

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

Copyright ©2024 Educative, Inc. All rights reserved