Scala (2-2) Collections (Tuple, Set and Map)

1. Tuple:

Tuples are immutable, but unlike lists, tuples can contain different types of elements.

val catInfo = ("Kitty", 4, "active")

The element can be accessed individually with a dot, underscore, and the one-based index of the element.

println(catInfo._1) // "Kitty"
println(catInfo._2) // 4
println(catInfo._3) // "active"

Note that the fields like _N numbers are one-based, instead of zero-based.


2. Set:

Scala provides mutable and immutable alternatives for sets. We can select the mutability of sets in the class hierarchy.

val zoo = Set("Bird", "Cat", "Dog")
println(zoo.getClass) // immutable.Set

The following syntax shows that zoo is a immutable:

zoo += "Fish" // error because zoo is immutable

There is a simple way to make the sets to be mutable, just import scala.collection.mutable.Set.

import scala.collection.mutable.Set

object Main extends App {
    val zoo = Set("Bird", "Cat", "Dog")
    zoo += "Fish"
    println(zoo.getClass()) // mutable.HashSet
    
}

The import syntax sets mutable.HashSet as default.

We can use var keyword to store the immutable sets.

object Main extends App {
    var zoo = Set("Bird", "Cat", "Dog")
    zoo += "Fish"         // create a new set  
    println(zoo.getClass) // immutable.Set
}

Whereas a mutable set will add the element to itself, an immutable set will create and return a new set with the element added.

Some useful methods of sets:

val zooA = Set("Bird", "Cat", "Dog")
val zooB = Set("Bird", "Cat", "Monkey")
println(zooA.intersect(zooB))    // Set(Bird, Cat)   
println(zooB.contains("Dog"))    // false
println(zooB.contains("Monkey")) // true

3. Map:

A Map is an Iterable consisting of pairs of keys and values.

We can create and initialize maps using factory methods similar to those used for arrays, lists, and sets.

val mathTest = Map(
    "Ben"->64,
    "Vicky"->80
)

println(mathTest)
println(mathTest.getClass) // immutable.Map

To use mutable maps, we need to import scala.collection.mutable.Map.

import scala.collection.mutable.Map

object Main extends App {
    val mathTest = Map(
        "Ben"->64,
        "Vicky"->80
    )
    mathTest += ("David"->90)
    
    println(mathTest)
    println(mathTest.getClass) // mutable.HashMap
}

留言

熱門文章