Summing up two options

前端 未结 4 946
误落风尘
误落风尘 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(_ + _)
    
    0 讨论(0)
  • 2021-02-08 22:39

    You could try this:

    for( x <- one.orElse(Some(0)); y <- two.orElse(Some(0))) yield x+y
    
    0 讨论(0)
  • 2021-02-08 22:53

    How about:

    one.map(_ + two.getOrElse(0)).orElse(two)
    
    0 讨论(0)
  • 2021-02-08 22:56

    obligatory scalaz answer is to use the scalaz Option monoid:

    scala> one |+| two
    res0: Option[Int] = Some(3)
    

    It will do what you want with respect to None:

    scala> two |+| None
    res1: Option[Int] = Some(2)
    
    scala> none[Int] |+| none[Int]
    res2: Option[Int] = None
    

    That none method is a method from scalaz which helps with type inference because instead of returning None <: Option[Nothing] it returns a Option[Int], there is a similar method from Some which returns an Option[A] for any given A instead of a Some[A]:

    scala> 1.some |+| 2.some
    res3: Option[Int] = Some(3)
    
    0 讨论(0)
提交回复
热议问题