Collections, Tuples and Maps

Traverable: It is the root trait of all collections and offers very important methods
maps: maps, flatMap, collect
conversions: toArray, toList, toSeq
size info: isEmpty, size, nonEmpty
tests: exists, forAll
folds: foldLeft, foldRight, reduceLeft, reduceRight
retrieval: head, find, tail
string ops: mkString

By default we use immutable collections in scala

package object scala {
    type List[+A] = immutable.List[A]

object Predef {
    type Map[A, +B] = immutable.Map[A, B]
    type Set[A] = immutable.Set[A]

Note: By default Seq apply method returns list
val aSeq = Seq(1, 3, 4, 2) // returns List
println(aSeq(2)) // overloaded apply method to get value at this index = prints 3

Tuple is an infinite ordered list. It has copy method similar to case classees.

    val aTuple = new Tuple2[Int, String](2, "Hello Scala") // Tuples can be extended to 22 different parameters to be in consistent with functions
    // is same as
    val aTuple1 = Tuple2(2, "Hello Scala")
    val aTuple2 = (2, "Hello Scala")
    val aTuple3 = (2 -> "Hello Scala")

    println(aTuple.copy(_2 = "Good Bye")) // copy methods similar to case classes
    println(aTuple.swap) // swaps key value positions


    val phoneBook = Map(("Jim", 555), ("Niran" -> 999)).withDefaultValue("-1")
    println(phoneBook("Mary")) // throws error if key is not found

    // add new pairing
    val newPairing = ("Mary" -> 909)
    val newPhonebook = phoneBook + newPairing

    // filterKeys
    // mapValues
    println(phoneBook.mapValues(number => "01245-" + number))
//    println(phoneBook.mapValues(number => number * 10))

    // conversions to other collections
    println(phoneBook.toList) // list of tuples
    println(List(("Niran" -> 57687)).toMap)

    val names = List("Niran", "Naveen", "Jim", "John")

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates


A topnotch site


Just another site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey