Scala Option object inside another Option object

后端 未结 4 2004
情书的邮戳
情书的邮戳 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 02:56

    The solution is to use Option.map and Option.flatMap:

    First.flatMap(_.second.flatMap(_.third.map(_.numberOfSmth)))
    

    Or the equivalent (see the update at the end of this answer):

    First flatMap(_.second) flatMap(_.third) map(_.numberOfSmth)
    

    This returns an Option[Int] (provided that numberOfSmth returns an Int). If any of the options in the call chain is None, the result will be None, otherwise it will be Some(count) where count is the value returned by numberOfSmth.

    Of course this can get ugly very fast. For this reason scala supports for comprehensions as a syntactic sugar. The above can be rewritten as:

    for { 
      first <- First
      second <- first .second
      third <- second.third
    } third.numberOfSmth
    

    Which is arguably nicer (especially if you are not yet used to seeing map/flatMap everywhere, as will certainly be the case after a while using scala), and generates the exact same code under the hood.

    For more background, you may check this other question: What is Scala's yield?

    UPDATE: Thanks to Ben James for pointing out that flatMap is associative. In other words x flatMap(y flatMap z))) is the same as x flatMap y flatMap z. While the latter is usually not shorter, it has the advantage of avoiding any nesting, which is easier to follow.

    Here is some illustration in the REPL (the 4 styles are equivalent, with the first two using flatMap nesting, the other two using flat chains of flatMap):

    scala> val l = Some(1,Some(2,Some(3,"aze")))
    l: Some[(Int, Some[(Int, Some[(Int, String)])])] = Some((1,Some((2,Some((3,aze))))))
    scala> l.flatMap(_._2.flatMap(_._2.map(_._2)))
    res22: Option[String] = Some(aze)
    scala> l flatMap(_._2 flatMap(_._2 map(_._2)))
    res23: Option[String] = Some(aze)
    scala> l flatMap(_._2) flatMap(_._2) map(_._2)
    res24: Option[String] = Some(aze)
    scala> l.flatMap(_._2).flatMap(_._2).map(_._2)
    res25: Option[String] = Some(aze)
    

提交回复
热议问题