12 / 17
Scala - Collections - Tuples and Maps

Unlike an array and list, tuples can hold elements of different data types. Let's create a tuple with elements 14, 45.69 and "Australia"). We can create it either with var t = (14, 45.69, "Australia") or with var t = Tuple3(14, 45.69, "Australia"). In the second syntax, we are explicitly specifying that tuple will contain 3 elements.

tuples can be accessed using a 1-based accessor for each value. To access the first element, type t._1. To access the third element type t._3

tuples can be deconstructed into names bound to each value in the tuple. Let us understand it. Type var (my_int, my_double, my_string) = t As you can see that, my_int is assigned 14, my_double is assigned 45.69 and my_string is assigned Australia

Tuples are immutable. Let us try to set the first element to 18. Type t._1 = 18. We have an error.

Scala maps are a collection of key/value pairs. Maps allow indexing values by a specific key for fast access. You can think of a Scala map as a Java Hashmap and Python dictionary.

Let's do a hands-on on Scala maps. Copy the code displayed on the screen. Colors map contains key/value pair of colors and their hex code. To see the hex code of color yellow, type colors("yellow"). As you can see, the hex code of yellow is #FFFF00. We can add new key/value pairs using += operator. Let's add color green and its hex value. Type colors += "green" -> "#008000" and press enter. Type colors to see the list of updated key/value pairs. We can remove key/value pair using -= operator. Let's remove key "red". Type colors -= "red" You can see that key "red" is no more in the map.

Let's iterate through colors map and print key/value pairs. Type the code displayed on the screen. Here we are iterating through colors map and printing the corresponding key and value.

Scala provides two types of maps - immutable and mutable. Please note by default, Scala uses the immutable Maps. It means that you can not change the value of a key. If you want to use the mutable maps, import scala.collection.mutable.Map class explicitly

Lab Details

Enroll now to learn and practice or Refer friends and get 15 days lab access

Enroll Now >>