我想在Scala中扩展可变Map,因为在添加新元组时我需要一些特殊的行为。 我有以下
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)
}
问题在于+=
方法的语法。它说方法+=
无法覆盖任何内容。如果我将+=
更改为+
,则存在类单元必须声明为抽象或实现抽象成员+=
的问题。
修改 这在语法上是正确的
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)
}
但最好扩展HashMap而不是Map,这是一个特性,因为我只需要改变一个函数来添加一个新的元组。
修改 而这正是我想要的。
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
}
答案 0 :(得分:4)
它应该被命名为+=
,但它的返回类型必须是Unit(因为它是一个可变的映射)并且你试图返回一个Map。请注意,您的类名为Unit,因此请小心。