Working With Scala Collections


We have a monthly iBAT (Inphina Beer and Technology Sessions). We look forward to this day and it was Scala day this time. I presented on Scala collections.

Scala collection is elegant and concise. Scala Collections like java is object-oriented and we can work with generic types. It is optionally persistent i.e can be mutable and immutable. It provides higher order methods like foreach, map and filter.

Scala collections follow uniform return type principle. Which basically means that when you perform an operation on a collection they return a collection of the same type.

The root Trait in Scala collections is Traversable. It may take some time to get used to it as Scala collections root Traits like Traversable have a big bunch of methods.

The for notation is more readable. It is basically like a for loop with a return type. Look for yourself how readable it is compared to the original code.

This code listing is without a for notation

scala> val listOfNumbers = List(1, 2, 3)
listOfNumbers: List[Int] = List(1, 2, 3)

scala> val flattenedListOfNumbers = listOfNumbers flatMap (0 to _)
flattenedListOfNumbers: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)

After using for notation

scala> val listOfNumbers = List(1, 2, 3)
listOfNumbers: List[Int] = List(1, 2, 3)

scala> val flattenedList = for(number <- listOfNumbers; range <- 0 to number) yield range
flattenedList: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)

One more interesting thing we can do with a Map is that we can reverse key and value with the following code

scala> val aMap = Map("India" -> "Delhi", "France" -> "Paris", "Italy" -> "Rome")
aMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(India -> Delhi, France -> Paris, Italy -> Rome)

scala> val reverseMap = aMap map{case(k, v) => (v, k)}
reverseMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Delhi -> India, Paris -> France, Rome -> Italy)

scala> val alsoReverseMap = for((k, v) <- aMap) yield (v -> k) 
alsoReverseMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Delhi -> India, Paris -> France, Rome -> Italy)

Reference were from Martin’s Odersky talk on Future Proofing Collections and Scala Collections API documentation. Enjoy the presentation …

This entry was posted in Scala and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s