list - Scala:对列表中的键/值对使用选项

标签 list scala key scala-option

我正在尝试为使用列表实现的键值对编写 get 方法。我想使用 Option 类型,因为我听说它对此很有用,但我是 Scala 新手,我不太确定在这种情况下如何使用它......

据我所知,这只是方法 header 。

def get(key : String): Option[Any] = {}

最佳答案

我猜你正在寻找这样的东西:

class KeyValueStore(pairs: List[(String, Any)]) {

  def get(key: String): Option[Any] = pairs.collectFirst {
    case (k, v) if k == key => v
  }

}

这对序列使用collectFirst 方法。如果您想要更多“自己动手”的方法,这应该可行:

def get(key: String): Option[Any] = {
  def search(xs: List[(String, Any)]): Option[Any] = {
    xs match {
      case List() => None //end of list and key not found. We return None
      case (k, v) :: rest if k == key => Some(v) // found our key. Returning some value
      case _ :: rest => search(rest) // not found until nou. Carrying on with the rest of the list
    }

    search(pairs)
  }
}

关于list - Scala:对列表中的键/值对使用选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18990427/

相关文章:

python - 为什么列表和元组会改变枚举的输出?

c++ - C++ 中带有继承类的链表?

xml - 如何跟踪 XML 元素的源代码行(位置)?

scala - Spark unionAll 多个数据帧

jquery - 确保在 keyup 事件上过滤 jquery 中的可打印字符

python - 在A列表中搜索一个元素的索引,如果没有找到,让用户知道

scala - Scala 模式匹配中无法访问的代码

mysql - phpmyadmin 导出后缺少外键约束

c# - 选择一个好的字典键

Python遍历目录并打开txt文件