我想建立一个这样的地图:
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 时将选项添加到列表中。
但一定有更优雅的方式。(例如,lift-json 知道如何在构造 JValue 时过滤掉 Options)。
有什么建议么?(PS我在这里简化了问题)