如何在 Scala 中向 Map 添加可选条目?
How to add optional entries to Map in Scala?
假设我要向 Map[Int, String]
添加类型为 Option[(Int, String)]
的可选条目
def foo(oe: Option[(Int, String)], map: Map[Int, String]) = oe.fold(map)(map + _)
现在我想知道如何添加几个个可选条目:
def foo(oe1: Option[(Int, String)],
oe2: Option[(Int, String)],
oe3: Option[(Int, String)],
map: Map[Int, String]): Map[Int, String] = ???
你会如何实施它?
map ++ Seq(oe1, oe2, oe3).flatten
如果可选条目的数量是可变的,我将使用可变长度参数
def foo(map: Map[Int, String], os: Option[(Int, String)]*) = map ++ os.flatten
正如我在上面的评论中提到的,Scala 提供了一个隐式转换 (option2Iterable
),允许您将 Option
用作一或零的 collection objects 在 collection 库中其他类型的上下文中。
这会产生一些恼人的后果,但它确实为您的操作提供了以下良好的语法:
def foo(oe1: Option[(Int, String)],
oe2: Option[(Int, String)],
oe3: Option[(Int, String)],
map: Map[Int, String]): Map[Int, String] = map ++ oe1 ++ oe2 ++ oe3
这是有效的,因为 Map
上的 ++
接受 GenTraversableOnce[(A, B)]
,而您从 option2Iterable
获得的 Iterable
是 [= 的子类型18=].
这种方法有很多变体。例如,您也可以写 map ++ Seq(oe1, oe2, oe3).flatten
。我觉得不太清楚,它涉及创建一个额外的 collection,但如果你喜欢它,那就去吧。
假设我要向 Map[Int, String]
Option[(Int, String)]
的可选条目
def foo(oe: Option[(Int, String)], map: Map[Int, String]) = oe.fold(map)(map + _)
现在我想知道如何添加几个个可选条目:
def foo(oe1: Option[(Int, String)],
oe2: Option[(Int, String)],
oe3: Option[(Int, String)],
map: Map[Int, String]): Map[Int, String] = ???
你会如何实施它?
map ++ Seq(oe1, oe2, oe3).flatten
如果可选条目的数量是可变的,我将使用可变长度参数
def foo(map: Map[Int, String], os: Option[(Int, String)]*) = map ++ os.flatten
正如我在上面的评论中提到的,Scala 提供了一个隐式转换 (option2Iterable
),允许您将 Option
用作一或零的 collection objects 在 collection 库中其他类型的上下文中。
这会产生一些恼人的后果,但它确实为您的操作提供了以下良好的语法:
def foo(oe1: Option[(Int, String)],
oe2: Option[(Int, String)],
oe3: Option[(Int, String)],
map: Map[Int, String]): Map[Int, String] = map ++ oe1 ++ oe2 ++ oe3
这是有效的,因为 Map
上的 ++
接受 GenTraversableOnce[(A, B)]
,而您从 option2Iterable
获得的 Iterable
是 [= 的子类型18=].
这种方法有很多变体。例如,您也可以写 map ++ Seq(oe1, oe2, oe3).flatten
。我觉得不太清楚,它涉及创建一个额外的 collection,但如果你喜欢它,那就去吧。