I will continue with some more data structures offered by Scala.
As Scala focuses on both imperative and functional programming, it offers both immutable and mutable implementations of below mentioned data structures:
1. Using Sets
scala> var jetSet = Set("Boeing","Airbus") jetSet: scala.collection.immutable.Set[java.lang.String] = Set(Boeing, Airbus) scala> println(jetSet) Set(Boeing, Airbus)
Using Set’s apply method (i.e. using parenthesis remember??), by default, it uses immutable implementation of Set as mentioned in the output.
scala.collection.mutable.* contains mutable implementations whereas
scala.collection.immutable.* contains immutable implementations.
“+=” method can be used to append to it. Mutable objects include them whereas immutable objects create new objects to incorporate new element.
scala> jetSet+="Lear" scala> println(jetSet) Set(Boeing, Airbus, Lear) scala> jetSet.+=("Lear2") scala> println(jetSet) Set(Boeing, Airbus, Lear, Lear2)
To use mutable set:
scala> import scala.collection.mutable.Set import scala.collection.mutable.Set scala> var mutableJetSet=Set("Boeing","Airbus") mutableJetSet: scala.collection.mutable.Set[java.lang.String] = Set(Airbus, Boeing) scala> mutableJetSet += "Lear" scala> println(mutableJetSet) Set(Airbus, Lear, Boeing)
HashSet is also available in both the implementations:
scala> var hashSet = HashSet("Tomatoes", "Potatoes") <console>:4: error: not found: value HashSet var hashSet = HashSet("Tomatoes", "Potatoes") ^ scala> import scala.collection.immutable.HashSet import scala.collection.immutable.HashSet scala> var hashSet = HashSet("Tomatoes", "Potatoes") hashSet: scala.collection.immutable.Set[java.lang.String] = Set(Tomatoes, Potatoes) scala> import scala.collection.mutable.HashSet import scala.collection.mutable.HashSet scala> var mutableHashSet = HashSet("Tomatoes", "Potatoes") mutableHashSet: scala.collection.mutable.Set[java.lang.String] = Set(Tomatoes, Potatoes)
2. Using Maps:
Again, they are both mutable and immutable available in the same packages.
scala> import scala.collection.mutable.Map import scala.collection.mutable.Map scala> val battingOrder = Map[Int, String]() battingOrder: scala.collection.mutable.Map[Int,String] = Map() scala> battingOrder += (1 -> "Shikhar Dhawan") scala> battingOrder += (2 -> "Rohit Sharma") scala> battingOrder += (3 -> "Virat Kohli") scala> println(battingOrder(2)) Rohit Sharma
Again, HashMap implementations are provided in both the packages.
Now, battingOrder += (2 -> "Rohit Sharma")
is internally converted by Scala Compiler as battingOrder.+=((2).->("Rohit Sharma"))
So, here first “->” method is called returning a tuple that is passed to “+=” method.
Pingback: Scala: Part 2: Arrays, List & Tuples | Rasesh Mori
Pingback: Scala: Part 4: Classes & Objects | Rasesh Mori