使用Scala的ObservableMap

时间:2011-07-09 00:39:52

标签: scala observablecollection publish-subscribe scala-2.9

我正在尝试使用scala.collection.mutable.ObservableMap。

我抓住from scala-user下方的片段并将其复制到REPL。

电子邮件提到已标记为已修复的票证2704,但此代码段不起作用。

语法是否已更改或订阅被错误地调用?

这是在2.9.0.final

scala> import scala.collection.mutable._

import scala.collection.mutable._

scala> import scala.collection.script._
import scala.collection.script._

scala> class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int,MyMap]
<console>:13: error: wrong number of type arguments for scala.collection.mutable.ObservableMap, should be 2
       class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int,MyMap]
                                                 ^

scala> class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int]
defined class MyMap

scala> val map = new MyMap
map: MyMap = Map()

scala> class MySub extends Subscriber[Message[(Int,Int)],MyMap] {
     | def notify(pub: MyMap, evt: Message[(Int,Int)]) { println(evt) }
     | }
defined class MySub

scala> val sub = new MySub
sub: MySub = MySub@49918c8f

scala> map.subscribe(sub)
<console>:18: error: type mismatch;
 found   : MySub
 required: map.Sub
       map.subscribe(sub)

1 个答案:

答案 0 :(得分:5)

问题在于MyMap没有改进Pub类型,因此MyMap需要Subscriber[Message[(Int, Int)] with Undoable, ObservableMap[Int, Int]],而您的订阅者类型为Subscriber[Message[(Int, Int)] with Undoable, MyMap]。有两种选择 - 更改订阅者以使Pub类型为ObservableMap[Int, Int]

import scala.collection.mutable._
import scala.collection.script._

class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int]
val map = new MyMap

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 sub = new MySub

map.subscribe(sub)

或更改MyMap以覆盖Pub类型:

import scala.collection.mutable._
import scala.collection.script._

class MyMap extends HashMap[Int,Int] with ObservableMap[Int,Int] {
  type Pub = MyMap
}
val map = new MyMap

class MySub extends Subscriber[Message[(Int,Int)] with Undoable, MyMap] {
  def notify(pub: MyMap, evt: Message[(Int,Int)] with Undoable) { println(evt) }
}
val sub = new MySub