Scala

11 / 17
Scala - Sequences and Sets

A sequence is an ordered collection of data. Elements in the sequence may or may not be indexed. Examples of sequence are array, list, and vector

An array contains elements of the same type. Arrays are fixed in size and contain an ordered sequence of data. Array values are contiguous in memory, which means that the values are stored in consecutive memory addresses. Array elements are indexed by position. In the code shown on the screen, variable language is an array which contains 3 elements of string type "Ruby", "SQL" and "Python". We access array elements by their indexes. Arrays have a zero-based index. To access the first element type languages(0). Arrays in Scala are mutable. We can change the values at specific indexes. To change "SQL" to "C++" type languages(1) = "C++"

To iterate over array elements we can use the 'for' loop. Let's iterate over languages array. Copy the code displayed on the screen. As you can see, each element of the languages array gets printed on the screen. The left arrow operator is called generator. We're iterating over the languages array one by one, assigning the element's value to x and printing x.

List in Scala represents a linked list having elements such that each element has a value and pointer to the next element. These lists have poor performance as data could be located anywhere in the memory. Compared to an array, a list is very flexible, as you do not have to worry about exceeding the size of the list. Theoretically, lists are unbounded in size, but practically their size is limited by the amount of memory allocated to the JVM.

Let us do a hands-on and create a list of integers 1, 2 and 3. Type var number_list = List(1, 2, 3). To add a new element to the list, type number_list:+ 4 As you can see, element 4 is added to the list. Let us try to change the value at index 1. Type number_list(1) = 7 We've got an error. We can not change the value since lists are immutable.

A set in Scala is a bag of data with no duplicates. Also, the ordering is not guaranteed in sets.

Let us create a set with integers 76, 5, 9, 1 and 2. Let us add 9 to it. Since duplicates are not allowed in sets, 9 is not added to the set. Let's add 20. We can see that 20 is added to the set. Note the order of 20. As discussed, set does not guarantee ordering. set(5) will result in boolean true as 5 is present in the set. set(14) will result in boolean false as 14 is not present in the set.

Lab Details


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


Enroll Now >>