Chapter 4 -- Scala for the Impatient
Chapter 4 -- Scala for the Impatient

Chapter 4 -- Scala for the Impatient
• 发表于 3年前
• 阅读 23
• 收藏 0
• 评论 0

``````    <!-- lang: scala -->
/////////// map  ///////////////////
// define a map, default type is a scala.collection.immutable.Map
val map1 = Map("alice" -> 12, "bob" -> 30)
// map1("alice") = 30

var map11 = Map("alice" -> 12, "bob" -> 30)
//map11("alice") = 23
// Above is a invalid statement as map1 is. So, identify "val" and "var" in this case is the same thing.

val map2 = new scala.collection.mutable.HashMap[String, Int]
// yep, this is a mutable map. So, what does "val" mean in this statement?
map2("ui") = 34
// So, map2 is a mutable variable whatever "val" or "var"

// another way to define a map
val map3 = Map(("alice", 23), ("bob", 30))

// get value from a map
val bobAge = map3("bob")
val _bobAge = if(map3.contains("bob")) map3("bob") else 0
val __bobAge = map3.getOrElse("bob", 0)

// update map
map2 += ("ux" -> 33, "leader" -> 40)
map2 -= "ui"

// iteration
for((k, v) <- map2) println(k + ":" + v)
for((k, v) <- map2) yield (v, k)

// sorted map
val sortedMap = scala.collection.immutable.SortedMap("alice" -> 10, "Fred" -> 7, "Bob" -> 3, "Cindy" -> 4)
val months = scala.collection.mutable.LinkedHashMap("Jan"-> 1, "Feb" -> 2, "Mar" -> 3)

/////////// tuple  ///////////////////
(1, 3.14, "Fred")
// Tuple3[Int, Double, java.lang.String]

val t = (1, 3.14, "Fred")
t._2 // value would be 3.14. So, tuple is 1 first.

val (first, second, third) = t // first: Int = 1   second: Double = 3.14   third: String = Fred
val (f, s, _) = t //f: Int = 1  s: Double = 3.14

// zip method
val symbols = Array("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs = symbols.zip(counts) // Array(("<", 2), ("-", 10), (">", 2))
``````

×