How do you stop building an Option[Collection] upon reaching the first None?

前端 未结 5 1328
夕颜
夕颜 2020-12-18 03:52

When building up a collection inside an Option, each attempt to make the next member of the collection might fail, making the collection as a whole a failure, t

5条回答
  •  清歌不尽
    2020-12-18 04:49

    I think your allParts2 function has a problem as one of the two branches of your match statement will perform a side effect. The return statement is the not-idiomatic bit, behaving as if you are doing an imperative jump.

    The first function looks better, but if you are concerned with the sub-optimal iteration that foldLeft could produce you should probably go for a recursive solution as the following:

    def allParts(names: Seq[String]): Option[Seq[Part]] = {
      @tailrec
      def allPartsRec(names: Seq[String], acc: Seq[String]): Option[Seq[String]] = names match {
        case Seq(x, xs@_*) => findPartByName(x) match {
          case Some(part) => allPartsRec(xs, acc +: part)
          case None => None
        }
        case _ => Some(acc)
      }
    
      allPartsRec(names, Seq.empty)
    }
    

    I didn't compile/run it but the idea should be there and I believe it is more idiomatic than using the return trick!

提交回复
热议问题