Scala Option object inside another Option object

后端 未结 4 2012
情书的邮戳
情书的邮戳 2021-02-08 02:05

I have a model, which has some Option fields, which contain another Option fields. For example:

case class First(second: Option[Second], name: Option[String])
ca         


        
4条回答
  •  佛祖请我去吃肉
    2021-02-08 03:02

    This can be done by chaining calls to flatMap:

    def getN(first: Option[First]): Option[Int] =
      first flatMap (_.second) flatMap (_.third) flatMap (_.numberOfSmth)
    

    You can also do this with a for-comprehension, but it's more verbose as it forces you to name each intermediate value:

    def getN(first: Option[First]): Option[Int] =
      for {
        f <- first
        s <- f.second
        t <- s.third
        n <- t.numberOfSmth
      } yield n
    

提交回复
热议问题