简体   繁体   English

清除Scala语法“将可选值附加到Seq(如果存在)”

[英]Clean Scala syntax for “Append optional value to Seq if it exists”

I often see these two patterns for appending an Optional value to a Seq: 我经常看到这两种模式用于向Seq附加一个Optional值:

def example1(fooList: Seq[Foo], maybeFoo: Option[Foo]): Seq[Foo]) = {
  if (maybeFoo.isDefined)
    fooList :+ maybeFoo.get
  else
    fooList
}

def example2(fooList: Seq[Foo], maybeFoo: Option[Foo]): Seq[Foo]) = {
  maybeFoo match {
    case Some(foo) => fooList :+ foo
    case None => fooList
  }
}

Both of those methods work, but they seem verbose and ugly. 这两种方法都有效,但它们看似冗长和丑陋。 Is there an existing operator or method to do this more naturally/functionally? 是否有现有的操作员或方法可以更自然地/功能性地完成此操作?

Thanks! 谢谢!

Option implicitly converts into a sequence with 1 or 0 items so the following works: Option隐式转换为包含1或0项的序列,因此以下工作原理:

scala> val opt = Some("a")
opt: Some[String] = Some(a)

scala> val nope = None
nope: None.type = None

scala> val seq = Seq("a", "b", "c")
seq: Seq[String] = List(a, b, c)

scala> seq ++ opt
res3: Seq[String] = List(a, b, c, a)

scala> seq ++ nope
res4: Seq[String] = List(a, b, c)
maybeFoo.foldLeft(fooList)(_ :+ _)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM