How to extend mutable Map in Scala

2019-08-06 19:38发布

问题:

I would like to extend mutable Map in Scala, because I need some special behaviour when adding a new tuple. I have the following

package my.package
import collection.mutable.Map

class Unit[T1,T2](map: Map[T1,T2]) extends Map[T1,T2]{
  override def get(key: T1): Option[T2] = super.get(key)
  override def iterator: Iterator[(T1, T2)] = super.iterator
  override def -=(key: T1): Map[T1, T2] = super.-(key)
  override def +=[T3 >: T2] (kv: (T1, T3)): Map[T1, T3] = super.+[T3](kv)
}

The problem is with the syntax of the += method. It says that method += overrides nothing. If I change += to +, there is an issue that class Unit must either be declared as abstract or implement abstract member +=.

EDIT This is syntacticly correct

class Unit[T1,T2] extends Map[T1,T2]{
  override def get(key: T1): Option[T2] = super.get(key)
  override def iterator: Iterator[(T1, T2)] = super.iterator
  override def -=(key: T1): Map[T1, T2] = super.-(key)
  override def += (kv: (T1, T2)): Map[T1, T2] = super.+[T2](kv)
}

But it would be better to extend HashMap instead of Map which is a trait, cause I need to change only one function for adding a new tuple.

EDIT And below this is what I wanted to have.

import collection.mutable.HashMap
import scala.math.{log,ceil}

class Unit[T1>:String,T2>:String] extends HashMap[T1,T2]{
  override def +=(kv: (T1, T2)): this.type = {
    val bits = ceil(log2(this.size)).toInt match {
      case x: Int if (x < 5) => 5
      case x => x
    }

    val key = Range(0,(bits - this.size.toBinaryString.size)).foldLeft("")((a,_)=>a+"0")+this.size.toBinaryString
    this.put(kv._1, key)
    this
  }
  val lnOf2 = log(2) // natural log of 2
  def log2(x: Double): Double = log(x) / lnOf2
}

回答1:

It's supposed to be named += but its return type must be Unit (since it's a mutable map) and you are trying to return a Map. Note that your class is named Unit so be careful there.