Given a Map[String, Int] in Scala, I want to create a trait that allows me to add extra logic to the add and get methods. What would be the correct syntax for doing this? (Note: I also want to invoke the super method in each case)
I tried something like:
var mymap: Map[String, Int] with mytrait[String, Int] = Map[String, Int]()
trait mytrait[A, B] {
abstract override def +[ B1 >: B] (kv: (A, B1)) : Map[A, B1] = { /* ... */ }
}
But the interpreter complains so I'm obviously missing something syntactically, specifically with the use of the type parameters.
Many thanks for the help
To be more specific: What I have is a map already in place in my code, and so rather than rewrite large chunks of my program, I want to add logic to the + method and get method of the Map so that it does extra logic every time items are added to the map elsewhere in the program. Hence why I opted for a trait to add functionality to the map
Here is my code at present :
trait RegManager[A, B] extends scala.collection.Map[A, B] {
case class KeyAlreadyExistsException(e: String) extends Exception(e)
abstract override def + [B1 >: B] (kv: (A, B1)): scala.collection.Map[A, B1] = {
super.+[B1](kv)
}
abstract override def get(key: A): Option[B] = super.get(key)
abstract override def iterator: Iterator[(A, B)] = super.iterator
abstract override def -(key: A): scala.collection.Map[A, B] = super.-(key)
}
var regs = new scala.collection.Map[String, Int] with RegManager[String, Int]
Update: In the end I opted for a wrapper style implementation (Decorator DP) which got the job done. I am only 6 months in to my Scala career so I might not have understood the capabilities of traits correctly yet?! Great language though!