Scala:连接 Option[List] 的两个实例
Scala: Concatonate two instances of Option[List]
鉴于以下情况:
val l1 = Some(List(1))
val l2 = Some(List(2))
我想连接 l1
和 l2
以便在两个选项都等于 None
时得到 List(1, 2)
或 Nil
。
如果有优雅的解决方案,我很乐意使用 scalaz。
l1.getOrElse(Nil) ::: l2.getOrElse(Nil)
还有这个选项:
List(l1, l2).flatMap(_.toList).flatten
可轻松用于任意数量的 Option[List[_]]
值
使用 cats library is much more simpler when you use the semigroup 输入 class
import cats._ , cats.implicits._ , cats.instances._
scala> Option(List(3)) |+| Option(List(5))
res0: Option[List[Int]] = Some(List(3, 5))
scala> Option(List(3)) |+| None
res1: Option[List[Int]] = Some(List(3))
鉴于以下情况:
val l1 = Some(List(1))
val l2 = Some(List(2))
我想连接 l1
和 l2
以便在两个选项都等于 None
时得到 List(1, 2)
或 Nil
。
如果有优雅的解决方案,我很乐意使用 scalaz。
l1.getOrElse(Nil) ::: l2.getOrElse(Nil)
还有这个选项:
List(l1, l2).flatMap(_.toList).flatten
可轻松用于任意数量的 Option[List[_]]
值
使用 cats library is much more simpler when you use the semigroup 输入 class
import cats._ , cats.implicits._ , cats.instances._
scala> Option(List(3)) |+| Option(List(5))
res0: Option[List[Int]] = Some(List(3, 5))
scala> Option(List(3)) |+| None
res1: Option[List[Int]] = Some(List(3))