我正在尝试为使用列表实现的键值对编写 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/