What does + = operation really do on a scala card?

As the code shows:

val map = scala.collection.mutable.Map[Int, Int]().withDefaultValue(0)
println(map(1))
map(1) = 10
println(map(1))
map(1) += 10
println(map(1))

and conclusion:

0
10
20

However, in my opinion, "map (1) + = 10" is invalid, as in java, and even correctly, the result after this line, map (1) should be 10.

So why??? and what exactly does the "+ =" operation do on the map?

+4
source share
3 answers

-, += , = . , ( Int +=), map(1) += 10 map(1) = map(1) + 10. Assignments map.update(1, map(1) + 10), map.update(1, map.apply(1) + 10), map - , .

+6

, " " + = " ?" . + = ( → ) Map, map () == .

, , map (1) + = 10.

  map(1) += 10

javacode

  24: invokestatic  #36                 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
  27: aload_2
  28: iconst_1
  29: invokestatic  #36                 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
  32: invokeinterface #43,  2           // InterfaceMethod scala/collection/mutable/Map.apply:(Ljava/lang/Object;)Ljava/lang/Object;
  37: invokestatic  #47                 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
  40: bipush        10
  42: iadd
  43: invokestatic  #36                 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
  46: invokeinterface #51,  3           // InterfaceMethod scala/collection/mutable/Map.update:(Ljava/lang/Object;Ljava/lang/Object;)V

- ( 24, 29, 37, 43). :

,

  27: aload_2
  28: iconst_1
  32: invokeinterface #43,  2           // InterfaceMethod scala/collection/mutable/Map.apply:(Ljava/lang/Object;)Ljava/lang/Object;

10:

  40: bipush        10
  42: iadd

:

  46: invokeinterface #51,  3           // InterfaceMethod scala/collection/mutable/Map.update:(Ljava/lang/Object;Ljava/lang/Object;)V

, (1) + = 10 map.update(1, map.apply(1) + 10)

+3

The Scala Map. +=means

ms += (k -> v)  Adds mapping from key k to value v to map ms as a side effect and returns ms itself.

ms += (k -> v, l -> w)  Adds the given mappings to ms as a side effect and returns ms itself.
0
source

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


All Articles