如何在Scala中扩展可变地图

如何在Scala中扩展可变地图

本文介绍了如何在Scala中扩展可变地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想在Scala中扩展可变Map,因为添加新的元组时我需要一些特殊的行为.我有以下

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)
}

问题出在+=方法的语法上.它说方法+=不会覆盖任何内容.如果将+=更改为+,则存在一个问题,即必须将类Unit声明为抽象或实现抽象成员+=.

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 +=.

编辑这在语法上是正确的

EDITThis 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)
}

但是最好扩展HashMap而不是Map,这是一个特性,因为我只需要更改一个函数即可添加新的元组.

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.

编辑而这就是我想要拥有的.

EDITAnd 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
}

推荐答案

应该将其命名为+=,但其返回类型必须为Unit(因为它是可变映射),因此您正在尝试返回Map.请注意,您的班级被命名为Unit,所以要小心.

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.

这篇关于如何在Scala中扩展可变地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:28