如何将scala中的序列转换/换行到Option [Seq],这样如果列表为空,则Option为None

时间:2017-02-24 18:13:27

标签: scala scala-option

我可以使用if语句执行此操作,但可能有一种“scala”方法可以执行此操作。

  def notScalaConv(in: Seq[String]): Option[Seq[String]] = {
    if (in.isEmpty)
      None
    else
      Option(in)
  }

2 个答案:

答案 0 :(得分:8)

您可以将Option提升为 def notScalaConv(in: Seq[String]): Option[Seq[String]] = { Option(in).filter(_.nonEmpty) } ,然后对其进行过滤。像这样:

def incrementCount(combiners: Array[Combiner], row: Row): Array[Combiner] = {
   val tempMapTypes = new scala.collection.mutable.HashMap[String, (String, Array[String])]
   for (i <- 0 until row.length) {
       val array = getMyType(row(i), tempMapTypes)
       for (elem <- tempMapTypes) {
         combiners(i).mapTypes.update(elem._1,elem._2) <<<< this update doesnt work for me, always mapTypes is empty
      }
    }
  }

答案 1 :(得分:-1)

为什么你不会只是val seqOpt = Option(yourSeq),这会给你Option(Seq[String])

  val nonEmpty = Seq("somevalue")
  val empty = Seq()

  val seqOpt = List(Option(empty), Option(nonEmpty)) map {
    case seq if seq.get.isEmpty => None
    case x => x
  }

  assert(seqOpt.head == None)
  assert(seqOpt(1) == Option(nonEmpty))