Using Scala's ObservableMap

♀尐吖头ヾ 提交于 2019-12-13 14:13:46

问题


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 = MySub@49918c8f

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

回答1:


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


来源:https://stackoverflow.com/questions/6631924/using-scalas-observablemap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!