Scala - why map.size returns 0 when the map is not empty

I am new to scala. In the following example, I'm a little confused what is happening. I created a modified map and then clicked three keys / values ​​on the map. I can get a queue with values ​​by key, but "web.keys" shows that the map is empty, and "web.size" returns 0! why is this and how can i get the correct card size?

scala> import scala.collection.mutable.{Map, Set, Queue, ArrayBuffer}

scala> val web = Map[Int, Queue[Long]]().withDefaultValue(Queue()) 
web: scala.collection.mutable.Map[Int,scala.collection.mutable.Queue[Long]] = Map()

scala> web(123).enqueue(567L)

scala> web(123).enqueue(1L)

scala> web(123).enqueue(2L)

scala> web(123)
res96: scala.collection.mutable.Queue[Long] = Queue(567, 1, 2)

scala> web
res97: scala.collection.mutable.Map[Int,scala.collection.mutable.Queue[Long]] = Map()

scala> web.size
res98: Int = 0

scala> web.keys
res99: Iterable[Int] = Set()

A simple map works great.

scala> val w= Map[Int,Int]()
w: scala.collection.mutable.Map[Int,Int] = Map()

scala> w(1)=1

scala> w
res10: scala.collection.mutable.Map[Int,Int] = Map(1 -> 1)

scala> w(2)=2

scala> w
res12: scala.collection.mutable.Map[Int,Int] = Map(2 -> 2, 1 -> 1)

scala> w.size
res13: Int = 2

I tried experimenting more, it looks like it has something to do with "withDefaultValue". But how can I fix this?

scala> val ww= Map[Int,Int]().withDefaultValue(0) 
ww: scala.collection.mutable.Map[Int,Int] = Map()

scala> ww
res14: scala.collection.mutable.Map[Int,Int] = Map()

scala> ww(1) += 1

scala> ww(2) += 2

scala>  w.size
res17: Int = 0
+4
source share
1 answer

When the default value is returned from the map, it is not added to the map! Therefore, when callingweb(123)

, . getOrElseUpdate . , -.

, :

web(123).enqueue(567L) 567L (). .

w(1)=1

ww(1) += 1 (0) 1.

map(K) K, map(K) = V V K.

, map(K) map(K) = V, . . http://otfried.org/scala/apply.html scala.

+5

Source: https://habr.com/ru/post/1687407/


All Articles