Pages

Monday, 28 March 2022

Difference between Scala Array, List, Tuple and Range


Scala Array

Collection Object of same data type

Update Element : Yes (Reassignment is allowed) - MUTABLE object

Examples :

Array (Define & assign values to each Array element)

scala> var cities = Array("NewYork", "London", "Paris", "Mumbai")
cities: Array[String] = Array(NewYork, London, Paris, Mumbai)

Update Array Element with new value 

scala> cities(1) = "Toronto"
scala> cities
res12: Array[String] = Array(NewYork, Toronto, Paris, Mumbai)

Create Empty Array

scala> var cities = new Array[String](5)
cities: Array[String] = Array(null, null, null, null, null)


Scala List

Collection Object of same data type

Update Element : No (Reassignment is NOT allowed) - IMMUTABLE object

Examples :

Array (Define & assign values to each Array element)

scala> var cities = List("NewYork", "London", "Paris", "Mumbai")
cities: List[String] = List(NewYork, London, Paris, Mumbai)

Update Array Element with new value 

scala> cities(1) = "Toronto"
<console>:13: error: value update is not a member of List[String]
       cities(1) = "Toronto" 

Create Empty List ( Use Nil )

scala> var cities = Nil
cities: scala.collection.immutable.Nil.type = List()

 

Scala Tuple

Ordered Container of same or different data type 

Elements to be defined >= 2.

Update Element : Cannot be defined as collection of element - IMMUTABLE object

Examples :

Declare/create Tuple

scala> val hadoopguru = ("Hadoop", "Guru", 2022, 99.99)
hadoopguru: (String, String, Int, Double) = (Hadoop,Guru,2022,99.99)


Scala Range

Range can be defined with start & end value (optional stepping value). We can also exclude end value with different syntax.

Update Element : Yes (Reassignment is NOT allowed) - IMMUTABLE object

Examples :

Range (Include end value)

scala> 1 to 10
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Range (Exclude end value)

scala> 1 until 10
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

Range (Include start & end with stepping value)

scala> 1 to 22 by 3
res4: scala.collection.immutable.Range = Range(1, 4, 7, 10, 13, 16, 19, 22) 

Range (Include start & exclude end with stepping value)

scala> 1 to 22 by 3
res4: scala.collection.immutable.Range = Range(1, 4, 7, 10, 13, 16, 19)



Keywords : scala interview questions, top 50, top 10, data engineer, collection object, loop.

No comments: