Ivan
Ivan

Reputation: 64207

How to extend a Map in Scala?

What I am trying to do is to write a custom class extending Map[DateTime, T]. The extended class is to take a Map[DateTime, T] as a constructor argument and call corresponding methods of the supplied map for every method a Map is to implement.

I had no problem writing

def -(key: DateTime) = iv.-(key)
def get(key: DateTime) = iv.get(key)

but I've got stuck on

+[B1 :>B](kv: (A, B1)):Map[A, B1]

How am I meant to write it?

Isn't there a simple reference Map wrapper implementation to start from?

PS: Don't offer to declare it as type DtMap[T] = Map[DateTime, T] - I am going to have to add my own methods into the class.

UPDATE: So, the result looks like this, to consolidate it so that somebody would be able to use it as a starting point for his Map extension (may the solution have some hidden problems - please let me know):

case class DtValMap[T](iv: Map[DateTime, T]) extends Map[DateTime, T] {
  def -(key: DateTime) = new DtValMap(iv.-(key))
  def get(key: DateTime) = iv.get(key)
  def +[T1 >: T](kv: (DateTime, T1)): DtValMap[T1] = new DtValMap(iv + kv)
  def iterator: Iterator[(DateTime, T)] = iv.iterator
}

UPDATE2: I've noticed the typo which was causing the problem now: I had :> (wrong) instead of >:. But I intentionally don't correct it in the text above as it would make the question make no sense.

Upvotes: 3

Views: 3613

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297205

Have you considered MapProxy? This has been deprecated on Scala 2.11, so this particular solution should be avoided.

Anyway, if you insist on extending Map and providing all of its API, what exactly is the problem with implementing +? Why doesn't this work?

def +[B1 >: T](kv: (DateTime, B1)):Map[DateTime, B1] = new YourMap(iv + kv)

Upvotes: 1

Didier Dupont
Didier Dupont

Reputation: 29528

If I understand correctly, there is

class YourMap[T](iv: Map[DateTime, T]) extends Map[DateTime, T] 

Can't you just do

def +[T1 >: T](kv: (DateTime, T1)): YourMap[T1] = new YourMap(iv + kv)

I'm not too sure about your def -, If I understand correctly, it returns a Map, not a YourMap. If this is ok, why can't you do just the same for +?

In the line of type DtMap[T], have you considered adding the method with pimp my library, rather than with class extension? Collection classes are complex, and so is extending them.

Upvotes: 1

Related Questions