2011-07-27 17 views
1

我是scala的新手。我希望在地圖被修改時得到通知。我認爲這可以使用可觀察的地圖來完成。scala中的observablemap

我試圖定義像下面

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

,但它不編譯說一個物體..

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 

爲什麼會這樣?你如何實例化一個ObservableMap?

+0

行..這可能是愚蠢的..我應該宣佈它爲HashMap .. –

回答

1

特徵ObseravableMap中的一些方法是抽象的,這意味着你必須提供它們的實現。這裏是API的link

您的代碼應該是這個樣子,當你完成:

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 
} 
+0

,但我認爲得到和迭代器應該是所有地圖通用..爲什麼每個人都應該提供自己的執行 –

+0

這是正確的,但你正在實例化一個'Map',這是一個特質本身。如果你想爲你提供'get'和'iterator'的實現,你需要實例化一個特定的映射,比如'HashMap'。 – agilesteel

+0

我會接受你的回答,讓我思考:) –

5

你需要一個具體的地圖類型混合ObservableMap

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() 
1

Map是具有它創建一個新的地圖實例,這就是爲什麼你可以做這樣的事情val mymap = Map()的應用方法的對象。但是你使用的地圖是一個特徵,它有一些你需要實現的抽象方法。由於MapObservableMap都具有抽象元素,因此它不起作用。

(我看到有人與我剛想說什麼回答,因爲我是typing-加勒特是正確的,你需要將它與具體類型混合)

另一種方法是創建一個MapProxy在你想觀察的地圖周圍,並將ObservableMap與那個混合起來。