在ObservableMap上调用update()时,不调用事件订阅者

时间:2012-05-31 15:09:51

标签: scala

我创建了一个ObservableMap,以及一个只打印它收到的任何事件的订阅者(取自here):

class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int]

class MySub extends Subscriber[Message[(Int,Int)] with Undoable, ObservableMap[Int, Int]] {
  def notify(pub: ObservableMap[Int, Int], evt: Message[(Int, Int)] with Undoable) { 
    println(evt)
  }
}

val map = new MyMap
map.subscribe(new MySub)

使用 + = ++ = - = 按预期工作:

scala> map += 1 -> 1
Include(NoLo,(1,1))
res5: map.type = Map(1 -> 1)

scala> map ++= Map(2 -> 4, 3 -> 9)
Include(NoLo,(3,9))
Include(NoLo,(2,4))
res6: map.type = Map(3 -> 9, 1 -> 1, 2 -> 4)

scala> map -= 1
Remove(NoLo,(1,1))
res7: map.type = Map(3 -> 9, 2 -> 4)

update 不起作用:

scala> map(4) = 16

scala> map
res9: MyMap = Map(3 -> 9, 4 -> 16, 2 -> 4)

为什么呢?看起来ObservableMap会覆盖 + = - = clear ++ = 更新似乎都是以 + = (由Growable和MapLike尊重)实现的,所以为什么它可以工作一个但不是另一个?

1 个答案:

答案 0 :(得分:3)

HashMap的可变版本调用update而后者调用put,它不调用+ =因此不会调用observable + =方法。我正在使用scala 2.9.1,但这应该与2.8 on相同。

来自HashMap:

  override def put(key: A, value: B): Option[B] = {
    val e = findEntry(key)
    if (e == null) { addEntry(new Entry(key, value)); None }
    else { val v = e.value; e.value = value; Some(v) }
  }

  override def update(key: A, value: B): Unit = put(key, value)

  def += (kv: (A, B)): this.type = { 
    val e = findEntry(kv._1)
    if (e == null) addEntry(new Entry(kv._1, kv._2))
    else e.value = kv._2
    this
  }