Reputation: 8621
Somehow, I can't seem to correctly implement a SortedMap. Here's a minimal (non-)working example:
class MyMap[A](t: Map[Long, A]) extends SortedMap[Long, A] {
protected val internalMap = TreeMap(t.toArray: _*)
def -(key: Long) = MyMap(internalMap - key)
def get(key: Long) = internalMap.get(key)
def rangeImpl(from: Option[Long], until: Option[Long]) = TreeMap(internalMap.rangeImpl(from, until))
def iterator = internalMap.iterator
def ordering = internalMap.ordering
}
But, whatever I pass into the MyMap
constructor, calling, for example, its size
, always returns 0.
Addendum: I just copy-pasted the code to a new project, and it worked 8-\ Anyway, let me change the question in order to make it useful: is this the correct way to extend SortedMap
?
Upvotes: 1
Views: 488
Reputation: 9259
After adding a couple of missing methods to make it compile, your code worked fine for me:
class MyMap[A](t: Map[Long, A]) extends SortedMap[Long, A] {
protected val internalMap = TreeMap(t.toArray: _*)
def +[B1 >: A](kv: (Long, B1)) = new MyMap(internalMap + kv)
def -(key: Long) = new MyMap(internalMap - key)
def get(key: Long) = internalMap.get(key)
def rangeImpl(from: Option[Long], until: Option[Long]) = internalMap.rangeImpl(from, until)
def iterator = internalMap.iterator
def ordering = internalMap.ordering
}
From the REPL:
scala> t
res5: Map[Long,String] = Map(123 -> abc, 456 -> def)
scala> new MyMap(t)
res6: MyMap[String] = Map(123 -> abc, 456 -> def)
scala> res6.size
res7: Int = 2
Am I missing something?
Upvotes: 3