gpt4 book ai didi

scala - 使用选项值构造 Map

转载 作者:行者123 更新时间:2023-12-04 17:54:34 26 4
gpt4 key购买 nike

我想构建一个这样的 map :

  def one = "one"
def two = "two"
def three = Some("three")

Map[String, String]("one" -> one, "two" -> two, "three" -> three)

这不会编译,因为方法三返回一个选项而不是字符串。
我可以像这样完成这项工作:
Map[String, String]("one" -> one, "two" -> two) ++ three.map(t => Map("three" -> t)).getOrElse(Map.empty[String, String])

现在它只会在它是 Some 时将 Option 添加到列表中。

但必须有更优雅的方式。 (例如,lift-json 知道如何在构建 JValue 时过滤掉选项)。

有什么建议?
(P.S.我在这里简化了问题)

最佳答案

Map("one" -> one, "two" -> two) ++ three.map("three" -> _)也会工作。

关于scala - 使用选项值构造 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11417039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com