简体   繁体   English

将Python字典重写为Scala多图(移植代码)?

[英]Rewrite Python dict to Scala multimap (Porting code)?

I'm trying to rewrite a python library to Scala for more compatibility with the new project . 我正在尝试将Python库重写为Scala,以实现与新项目的更多兼容性。 The Python version had some inMemoryStorage based on a dict 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, [])

My scala version is not quite there yet not sure hot to improve it since I'm new to scala porting it is getting really hard. 我的scala版本还不存在,但不确定要改进它的热门之处,因为我不熟悉scala移植,这真的很难。 What am i missing? 我想念什么? Is this a close enough rewrite? 这足够接近重写吗?

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

You are on the right track, the set_val needs to override the initial (key, value) (if present) and start afresh (as seen from python code): 您处在正确的轨道上, 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)
}

Also, as the internalStorage is being accessed only using Storage, you might want to make it private . 另外,由于只能使用Storage访问internalStorage ,因此您可能希望将其设为private

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM