Summing up two options

前端 未结 4 963
误落风尘
误落风尘 2021-02-08 22:10

Let\'s say I have two optional Ints (both can be Some or None):

val one : Option[Int] = Some(1)
val two : Option[Int] = Some(2)

My question is

4条回答
  •  忘掉有多难
    2021-02-08 22:37

    for (x <-one; y <- two) yield x+y
    

    Or the less readable but strictly equivalent:

    one.flatMap{x=>two.map(x+_)}
    

    UPDATE: As your latest edit made quite clear, you only want a None as the result when both the input options are None. In this case I don't think you'll get anything better in terms of simplicity than what you already use. I could shorten it a bit but overall this is just the same:

    (one ++ two).reduceOption(_ + _)
    

提交回复
热议问题