Using Scala's ObservableMap
I'm trying to use scala.collection.mutable.ObservableMap.
I grabbed the snippet below from scala-user and copied it to the REPL.
The email mentions ticket 2704 which has been marked as fixed but this snippet does not work.
So has the syntax changed or is subscribe being called incorrectly?
This is on 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 = MyS开发者_如何学Goub@49918c8f
scala> map.subscribe(sub)
<console>:18: error: type mismatch;
found : MySub
required: map.Sub
map.subscribe(sub)
The problem here is that MyMap isn't refining the Pub type, so MyMap wants a Subscriber[Message[(Int, Int)] with Undoable, ObservableMap[Int, Int]]
and your subscriber type is Subscriber[Message[(Int, Int)] with Undoable, MyMap]
. There are two options -- either change your subscriber so that the Pub
type is 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)
or, change MyMap to override the Pub type:
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
精彩评论