Map 特质也包含了多个可变和不可变的具体实现类。
scala> val t="a"->1 val t: (String, Int) = (a,1) scala> val t2=("a",1) val t2: (String, Int) = (a,1) scala> val t3=Tuple2("a",1) val t3: (String, Int) = (a,1)
val m =Map(t)
scala> val m=Map("a"->1,"b"->2,"c"->3) val m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3) scala> m.get("a") val res156: Option[Int] = Some(1) scala> m.get("z") val res157: Option[Int] = None scala> m.getOrElse("z",100) val res159: Int = 100 scala> m("a") val res160: Int = 1 scala> m("z") java.util.NoSuchElementException: key not found: z at scala.collection.immutable.Map$Map3.apply(Map.scala:399) ... 32 elided scala> val m2=m.withDefault(_.charAt(0)-'a') val m2: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3) scala> val m3=m.withDefaultValue(-1) val m3: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3) scala> m2("z") val res162: Int = 25 scala> m2("y") val res163: Int = 24 scala> m3("z") val res164: Int = -1
contains isDefinedAt
scala> m.contains("a") val res171: Boolean = true scala> m.contains("z") val res172: Boolean = false scala> m.isDefinedAt("a") val res175: Boolean = true scala> m.isDefinedAt("z") val res176: Boolean = false