1
votes

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 wants overrides for + and - methods, but not for what you've mentioned. - vvg
if I override method + and - it says: class Unit must either be declared as abstract or implement abstract member -= and += - Szymon Roziewski
Don't assignments evaluate to Unit? I.e. shouldn't the return type be Unit? - Jörg W Mittag
I have just removed [T3 >: T2] and changed T3 to T2, because it wasn't necessary, and syntax is alright. The thing was that I wanted to extend an abstract class which is a bunch of work. I would go for extending HashMap cause I need to change only one function. - Szymon Roziewski
@Szymon Roziewski Hey, just checking if this is resolved - slouc

1 Answers

4
votes

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.