开发者

observablemap in scala

I am new to scala. I want to be notified whenever a map is modified. I thought this can be done using a observable map.

I am trying to define a object like below

var myObj = new Map[UUID, MyType] with ObservableMap[UUID,MyType]

but it does not compile saying..

开发者_如何学C
error: object creation impossible, since:
method iterator in trait MapLike of type => Iterator[(java.util.UUID, MyType)] is not defined
method get in trait MapLike of type (key: java.util.UUID)Option[MyType] is not defined
method -= in trait ObservableMap of type (key: java.util.UUID)this.type is marked `abstract' and `override', but no concrete implementation could be found in a base class
method += in trait ObservableMap of type (kv: (java.util.UUID, MyType))this.type is marked `abstract' and `override', but no concrete implementation could be found in a base class

why is this so? How do you instantiate a ObservableMap?


You need to mix ObservableMap in with a concrete map type.

scala> import scala.collection.mutable._
import scala.collection.mutable._

scala> val map = new HashMap[Int, Int] with ObservableMap[Int, Int]
map: scala.collection.mutable.HashMap[Int,Int] with scala.collection.mutable.ObservableMap[Int,Int] = Map()


Some of the methods in the trait ObseravableMap are abstract, which means you have to provide their implementations. Here is the link to the API.

Your code should look something like this when your are done:

val myObj = new Map[UUID, MyType] with ObservableMap[UUID, MyType] {
   def get (key: A): Option[B] = // your implementation here
   def iterator : Iterator[(A, B)] = // your implementation here
}


Map is an object that has an apply method which creates a new map instance, which is why you can do things like val mymap = Map(). But the map you're using is a trait, which has some abstract methods that you need to implement. Since both Map and ObservableMap have abstract elements, it doesn't work.

(I see that someone answered with what I was about to say, as I was typing- Garrett is right, you need to mix it in with a concrete type)

An alternative would be to create a MapProxy around the map you want to observe, and mix the ObservableMap with that.


this is trait is meant to be used as a mixin. like:

val map = new HashMap[_,_] with ObservableMap[_,_]

however it's deprecated since scala_2.11.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜