【问题标题】:Add Option[T] to Vector[T]将 Option[T] 添加到 Vector[T]
【发布时间】:2020-04-02 16:04:43
【问题描述】:

执行此类操作的最佳做​​法是什么?如果TSome[T],则将T 添加到Vector[T],否则什么也不做。这个丑陋的东西有效

val v: Vector[Int] = Vector(1, 2, 3) ++ Some(5).toSeq

但是将 Option 转换为 Seq 远非直观。我正在考虑为 VectorOption 定义一个隐式,但我想知道是否有现成可用的东西。

我希望这样的东西可以工作

   val v: Vector[Int] = Vector(1, 2, 3) :+ Some(5) 

但显然Option is NOT Traversable.

【问题讨论】:

    标签: scala


    【解决方案1】:

    Vector(1, 2, 3) ++ Some(5).toSeq没有什么问题,通常都是这样处理的。

    在尝试使用代码回答您的问题时,我发现(令我惊讶的是)即使在 Scala 2.10 - 2.12 中,您也不必编写 toSeq,这要归功于在 scala.Option 伴随对象中定义的 option2Iterable。这种隐式转换确保 Option 可以在需要 Iterable 的地方使用,这对于 Vector.++ 运算符来说已经足够了。

    以下作品:Vector(1, 2, 3) ++ Some(5)

    您不需要使用toSeq,即使连接多个选项,例如Some(1) ++ Some(2) - 结果是List(1, 2)

    在 Scala 2.13 中,Option 派生自 IterableOnce,因此即使是隐式转换也没有必要。

    【讨论】:

      【解决方案2】:

      Option 在 Scala 2.13 中由Make Option extend IterableOnce #8038 制作为IterableOnce

      sealed abstract class Option[+A] extends IterableOnce[A] with Product with Serializable
      

      所以以下应该适用于 Scala 2.13

      Vector(1, 2, 3) ++ Some(5)
      Vector(1, 2, 3) ++ None
      // res1: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 5)
      // res2: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
      

      【讨论】:

        【解决方案3】:

        我会模式匹配它。

        val v: Vector[Int] = optional match {
          case Some(x) => Vector(1, 2, 3) :+ x
          case None => Vector(1, 2, 3)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-23
          • 1970-01-01
          • 2012-06-21
          相关资源
          最近更新 更多