Combining 2 Options into 1

前端 未结 3 1072
夕颜
夕颜 2020-12-11 14:57

Is there a predefined function x in Scala that combine 2 Options so that

Some(a) x None => Some(a)
None x Some(b) => Some(b)
None x None => None


        
相关标签:
3条回答
  • 2020-12-11 15:05

    Yes, this is the orElse method. It chooses the first defined value, or None if neither is defined.

    scala> Some(1) orElse None
    res0: Option[Int] = Some(1)
    
    scala> None orElse Some(1)
    res1: Option[Int] = Some(1)
    
    scala> None orElse None
    res2: Option[Nothing] = None
    
    scala> Some(1) orElse Some(2)
    res3: Option[Int] = Some(1)
    
    0 讨论(0)
  • 2020-12-11 15:20

    In the question comments, you mention you can't have Some(a) and Some(b), so what you really have is Option[Either[Int,Int]]. In that case, you can use x.map(_.merge) to get back to Option[Int], eg

    scala> val x:Option[Either[Int,Int]] = Some(Left(2))
    x: Option[Either[Int,Int]] = Some(Left(2))
    
    scala> x.map(_.merge)
    res0: Option[Int] = Some(2)
    
    0 讨论(0)
  • 2020-12-11 15:25

    It's not hard to do it by hand:

    scala> val a = Some(1)
    a: Some[Int] = Some(1)
    
    scala> val b = Some(2)
    b: Some[Int] = Some(2)
    
    scala> Seq(a,b).flatten.headOption
    res0: Option[Int] = Some(1)
    
    0 讨论(0)
提交回复
热议问题