将Python dict重写为Scala multimap(移植代码)?

时间:2014-12-21 07:21:44

标签: python scala dictionary porting multimap

我正在尝试将一个python库重写为Scala,以便与新项目更加兼容。 Python版本有一些基于dict的inMemoryStorage

class InMemoryStorage(BaseStorage):
  def __init__(self, config):
    self.name = 'dict'
    self.storage = dict()

  def keys(self):
    return self.storage.keys()

  def set_val(self, key, val):
    self.storage[key] = val

  def get_val(self, key):
    return self.storage[key]

  def append_val(self, key, val):
    self.storage.setdefault(key, []).append(val)

  def get_list(self, key):
    return self.storage.get(key, [])

我的scala版本还不完全存在但还不确定要改进它,因为我刚接触scala移植它变得非常困难。我错过了什么?这是否足够接近重写?

class Storage {
  val internalStorage=new HashMap[String, Set[String]] with MultiMap[String, String]

  def keys():Iterable[String]={
    internalStorage.keys
  }

  def set_val(key:String,value:String)={
    internalStorage.addBinding(key,value)
  }

  def get_val( key:String):Set[String]= {
    return internalStorage(key)
  }

  def append_val( key:String, value:String)={
    internalStorage.addBinding(key,value)
  }

  def get_list(key:String):Set[String]={
    internalStorage(key)
  }
}

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上,set_val需要覆盖初始(key, value)(如果存在)并重新开始(从python代码中看到):

def set_val(key:String,value:String)={
  if (internalStorage.contains(key)) 
    internalStorage.remove(key); // to start fresh
  internalStorage.addBinding(key,value)
}

此外,由于仅使用存储访问internalStorage,您可能希望将其设为private

private[this] val internalStorage=new HashMap[String, Set[String]] with MultiMap[String, String]