Lists

As discussed earlier, Scala provides mutable and immutable collections. The Immutable collections are imported by default, but if you need to use a mutable one you need to import yourself. A list is an immutable collections, and it can be used if you want order between the elements to be preserved and duplicates to be kept. Let's demonstrate an example and see how lists preserve order and keep duplicated elements, and also check its immutability:

scala> val numbers = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
numbers: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
scala> numbers(3) = 10

<console>:12: error: value update is not a member of List[Int]
numbers(3) = 10 ^

You can define lists using two different building blocks. Nil represents the tail of the List and, afterwards, an empty List. So, the preceding example can be rewritten as:

scala> val numbers = 1 :: 2 :: 3 :: 4 :: 5 :: 1 :: 2 :: 3:: 4:: 5 :: Nil
numbers: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3,4, 5

Let's check lists with its method in the following detailed example:

package com.chapter4.CollectionAPI

object ListExample {
def main(args: Array[String]) {
// List of cities
val cities = "Dublin" :: "London" :: "NY" :: Nil

// List of Even Numbers
val nums = 2 :: 4 :: 6 :: 8 :: Nil

// Empty List.
val empty = Nil

// Two dimensional list
val dim = 1 :: 2 :: 3 :: Nil ::
4 :: 5 :: 6 :: Nil ::
7 :: 8 :: 9 :: Nil :: Nil
val temp = Nil

// Getting the first element in the list
println( "Head of cities : " + cities.head )

// Getting all the elements but the last one
println( "Tail of cities : " + cities.tail )

//Checking if cities/temp list is empty
println( "Check if cities is empty : " + cities.isEmpty )
println( "Check if temp is empty : " + temp.isEmpty )

val citiesEurope = "Dublin" :: "London" :: "Berlin" :: Nil
val citiesTurkey = "Istanbul" :: "Ankara" :: Nil

//Concatenate two or more lists with :::
var citiesConcatenated = citiesEurope ::: citiesTurkey
println( "citiesEurope ::: citiesTurkey : "+citiesConcatenated )

// using the concat method
citiesConcatenated = List.concat(citiesEurope, citiesTurkey)
println( "List.concat(citiesEurope, citiesTurkey) : " +
citiesConcatenated )

}
}

You will get the following output:

Head of cities : Dublin
Tail of cities : List(London, NY)
Check if cities is empty : false
Check if temp is empty : true
citiesEurope ::: citiesTurkey : List(Dublin, London, Berlin, Istanbul, Ankara)
List.concat(citiesEurope, citiesTurkey) : List(Dublin, London, Berlin, Istanbul, Ankara)

Now, let's see another quick overview of how to use sets in your Scala application in the next subsection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.217.55